Programs & Examples On #Mail server

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Something like this (sounds like you just need to change your SMTP server):

String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
    i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
    i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();

Change Background color (css property) using Jquery

Change Background Color using on click button jquery

Below is the code of jquery, which you can put in your head tag.

jQuery Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
      $("button").click(function(){
        $("div").addClass("myclass");
      });
    });
</script>

CSS Code:

<style>
    .myclass {
        background-color: red;
        padding: 100px;
        color: #fff;
    }
</style>

HTML Code:

<body>
    <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    <button>Click Here</button>
</body>

Why does Vim save files with a ~ extension?

:set nobackup 

will turn off backups. You can also set a backupdir if you still want those backup files but in a central folder. This way your working dir is not littered with ~ files.

You find more information on backups under :he backup.

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

+----------+
|       _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

Python: Figure out local timezone

You may be happy with pendulum

>>> pendulum.datetime(2015, 2, 5, tz='local').timezone.name
'Israel'

Pendulum has a well designed API for manipulating dates. Everything is TZ-aware.

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

First must be Alphabet and then dot not allowed in target string. below is code.

        string input = "A_aaA";

        // B
        // The regular expression we use to match
        Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.

        // C
        // Match the input and write results
        Match match = r1.Match(input);
        if (match.Success)
        {
            Console.WriteLine("Valid: {0}", match.Value);

        }
        else
        {
            Console.WriteLine("Not Match");
        }


        Console.ReadLine();

How to fill a datatable with List<T>

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

AngularJS: How to run additional code after AngularJS has rendered a template?

You can use the 'jQuery Passthrough' module of the angular-ui utils. I successfully binded a jQuery touch carousel plugin to some images that I retrieve async from a web service and render them with ng-repeat.

How to define dimens.xml for every different screen size in android?

Android 3.2 introduces a new approach to screen sizes,the numbers describing the screen size are all in “dp” units.Mostly we can use

smallest width dp: the smallest width available for application layout in “dp” units; this is the smallest width dp that you will ever encounter in any rotation of the display.

To create one right click on res >>> new >>> Android resource directory

From Available qualifiers window move Smallest Screen Width to Chosen qualifiers

In Screen width window just write the "dp" value starting from you would like Android Studio to use that dimens.

Than change to Project view,right click on your new created resource directory

new >>> Values resource file enter a new file name dimens.xml and you are done.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

Try adding the drive letter:

include_path='.;c:\xampplite\php\pear\PEAR'

also verify that PEAR.php is actually there, it might be in \php\ instead:

include_path='.;c:\xampplite\php'

JavaScript ternary operator example with functions

I would also like to add something from me.

Other possible syntax to call functions with the ternary operator, would be:

(condition ? fn1 : fn2)();

It can be handy if you have to pass the same list of parameters to both functions, so you have to write them only once.

(condition ? fn1 : fn2)(arg1, arg2, arg3, arg4, arg5);

You can use the ternary operator even with member function names, which I personally like very much to save space:

$('.some-element')[showThisElement ? 'addClass' : 'removeClass']('visible');

or

$('.some-element')[(showThisElement ? 'add' : 'remove') + 'Class']('visible');

Another example:

var addToEnd = true; //or false
var list = [1,2,3,4];
list[addToEnd ? 'push' : 'unshift'](5);

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

In my case I need both XAMPP for Apache development & IIS Express for .Net 2013 development; so I do the following:

  1. In Command Prompt typed services.msc, this loads "Windows Services" where I located "World Wide Web Publishing Service" and stop it. World Wide Web Publishing Service STOP

  2. The I start XAMPP Control Panel click on "Config", then choose "Apache httpd.conf". Search for "80" then change that to "8080" in both "Listen 80" and "ServerName localhost:80". Save the file from "Save As" & choose "All files" to not save it as text from "Save As Type" & the "Encoding" should be "UTF-8". Apache httpd.conf

  3. Quit XAMPP Control Panel, then start it again and from "Action" start Apache & MySQL. Now you will see the port changed. As you know now you have to get to your Apache server by using "localhost:8080" instead of "localhost". Also you have both Apache & IIS Express running in the same Windows 10 PC.

I read a post some where were the writer suggested to use port "9080" but it did not work for me.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

What's a good, free serial port monitor for reverse-engineering?

I've been down this road and eventually opted for a hardware data scope that does non-instrusive in-line monitoring. The software solutions that I tried didn't work for me. If you had a spare PC you could probably build one, albeit rather bulky. This software data scope may work, as might this, but I haven't tried either.

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

Twitter Bootstrap add active class to li

Just in case you are using Boostrap in Angulajs: this is a simple directive that works for me (because data-toggle cited by Kam is not included in Angular-ui). Hope can help.

app.directive("myDataToggle", function(){
    function link(scope, element, attrs) {
        var e = angular.element(element);
        e.on('click', function(){
            e.parent().parent().children().removeClass('active');
            e.parent().addClass("active");
        })
    }
    return {
        restrict: 'A',
        link: link
    };
});

<ul class="nav nav-sidebar">
    <li><a href="#/page1" my-data-toggle>Page1</a></li>
    <li><a href="#/page2" my-data-toggle>Page2</a></li>
    <li><a href="#/page3" my-data-toggle>Page3</a></li>
</ul>

Fatal error: Call to undefined function curl_init()

There is solution with all necessary details for Windows 7 x64:

http://www.youtube.com/watch?v=7qNTi1sEfE8

It is in French, but you can understand everything! I solved same problem, even don't speak French. :-)

Many answers forget to mention that you need to add new version of php_curl.dll file from this location: http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/

I added new version of php_curl.dll from archive php_curl-5.4.3-VC9-x64.zip to folders: C:\wamp\bin\php\php5.4.3\ext and C:\Windows\System32 and everything was fine!

Create unique constraint with null columns

You can store favourites with no associated menu in a separate table:

CREATE TABLE FavoriteWithoutMenu
(
  FavoriteWithoutMenuId uuid NOT NULL, --Primary key
  UserId uuid NOT NULL,
  RecipeId uuid NOT NULL,
  UNIQUE KEY (UserId, RecipeId)
)

Can I embed a .png image into an html page?

I don't know for how long this post has been here. But I stumbled upon similar problem now. Hence posting the solution so that it might help others.

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;

use GD::Graph::pie;
use MIME::Base64;
my @data = (['A','O','S','I'],[3,16,12,47]);

my $mygraph = GD::Graph::pie->new(200, 200);
my $myimage = $mygraph->plot(\@data)->png;

print <<end_html;
<html><head><title>Current Stats</title></head>
<body>
<p align="center">
<img src="data:image/png;base64,
end_html

print encode_base64($myimage);

print <<end_html;
" style="width: 888px; height: 598px; border-width: 2px; border-style: solid;" /></p>
</body>
</html>

end_html

Passing data through intent using Serializable

Intent intent = new Intent(getApplicationContext(),SomeClass.class);
intent.putExtra("value",all_thumbs);
startActivity(intent);

In SomeClass.java

Bundle b = getIntent().getExtras();
if(b != null)
thumbs = (List<Thumbnail>) b.getSerializable("value");

Java collections maintaining insertion order

The collections don't maintain order of insertion. Some just default to add a new value at the end. Maintaining order of insertion is only useful if you prioritize the objects by it or use it to sort objects in some way.

As for why some collections maintain it by default and others don't, this is mostly caused by the implementation and only sometimes part of the collections definition.

  • Lists maintain insertion order as just adding a new entry at the end or the beginning is the fastest implementation of the add(Object ) method.

  • Sets The HashSet and TreeSet implementations don't maintain insertion order as the objects are sorted for fast lookup and maintaining insertion order would require additional memory. This results in a performance gain since insertion order is almost never interesting for Sets.

  • ArrayDeque a deque can used for simple que and stack so you want to have ''first in first out'' or ''first in last out'' behaviour, both require that the ArrayDeque maintains insertion order. In this case the insertion order is maintained as a central part of the classes contract.

How to limit depth for recursive file list?

Make use of find's options

There is actually no exec of /bin/ls needed;

Find has an option that does just that:

find . -maxdepth 2 -type d -ls

To see only the one level of subdirectories you are interested in, add -mindepth to the same level as -maxdepth:

find . -mindepth 2 -maxdepth 2 -type d -ls

Use output formatting

When the details that get shown should be different, -printf can show any detail about a file in custom format; To show the symbolic permissions and the owner name of the file, use -printf with %M and %u in the format.

I noticed later you want the full ownership information, which includes the group. Use %g in the format for the symbolic name, or %G for the group id (like also %U for numeric user id)

find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'

This should give you just the details you need, for just the right files.

I will give an example that shows actually different values for user and group:

$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data  www-data /tmp/user/33
drwx------ octopussy root     /tmp/user/126
drwx------ root      root     /tmp/user/0
drwx------ siegel    root     /tmp/user/1000
drwxrwxrwt root      root     /tmp/systemd-[...].service-HRUQmm/tmp

(Edited for readability: indented, shortened last line)


Notes on performance

Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:

Not only do we save creating a new process for each name - a huge task - the information does not even need to be read, as find already knows it.

Programmatically navigate to another view controller/scene

Swift 4.0.3

 @IBAction func registerNewUserButtonTapped(_ sender: Any) {

        print("---------------------------registerNewUserButtonTapped --------------------------- ");

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "RegisterNewUserViewController") as! RegisterNewUserViewController
        self.present(nextViewController, animated:true, completion:nil)

    }

Change our Controller Name RegisterNewUserViewController

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

Why do some functions have underscores "__" before and after the function name?

Names surrounded by double underscores are "special" to Python. They're listed in the Python Language Reference, section 3, "Data model".

How can I analyze a heap dump in IntelliJ? (memory leak)

I would like to update the answers above to 2018 and say to use both VisualVM and Eclipse MAT.

How to use:

VisualVM is used for live monitoring and dump heap. You can also analyze the heap dumps there with great power, however MAT have more capabilities (such as automatic analysis to find leaks) and therefore, I read the VisualVM dump output (.hprof file) into MAT.



Get VisualVM:

Download VisualVM here: https://visualvm.github.io/

You also need to download the plugin for Intellij: enter image description here

Then you'll see in intellij another 2 new orange icons: enter image description here

Once you run your app with an orange one, in VisualVM you'll see your process on the left, and data on the right. Sit some time and learn this tool, it is very powerful: enter image description here



Get Eclipse's Memory Analysis Tool (MAT) as a standalone:

Download here: https://www.eclipse.org/mat/downloads.php

And this is how it looks: enter image description here enter image description here

Hope it helps!

Dump Mongo Collection into JSON format

Here's mine command for reference:

mongoexport --db AppDB --collection files --pretty --out output.json

On Windows 7 (MongoDB 3.4), one has to move the cmd to the place where mongod.exe and mongo.exe file resides => C:\MongoDB\Server\3.4\bin else it won't work saying it does not recongnize mongoexport command.

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

This appears to fit what you are looking for: https://forums.oracle.com/forums/thread.jspa?threadID=2140801

Basically, you will need to use regular expressions as there appears to be nothing built into oracle for this.

I pulled out the example from the thread and converted it for your purposes. I suck at regex's, though, so that might need tweaked :)

SELECT  *
FROM myTable m
WHERE NOT regexp_like(m.status,'((Done^|Finished except^|In Progress^)')

Retrieving parameters from a URL

parameters = dict([part.split('=') for part in get_parsed_url[4].split('&')])

This one is simple. The variable parameters will contain a dictionary of all the parameters.

Access Control Origin Header error using Axios in React Web throwing error in Chrome

npm i cors
const app = require('express')()
app.use(cors())

Above code worked for me.

How to remove word wrap from textarea?

I found a way to make a textarea with all this working at the same time:

  • With horizontal scrollbar
  • Supporting multiline text
  • Text not wrapping

It works well on:

  • Chrome 15.0.874.120
  • Firefox 7.0.1
  • Opera 11.52 (1100)
  • Safari 5.1 (7534.50)
  • IE 8.0.6001.18702

Let me explain how i get to that: I was using Chrome inspector integrated tool and I saw values on CSS styles, so I try these values, instead of normal ones... trial & errors till I got it reduced to minimum and here it is for anyone that wants it.

In the CSS section I used just this for Chrome, Firefox, Opera and Safari:

textarea {
  white-space:nowrap;
  overflow:scroll;
}

In the CSS section I used just this for IE:

textarea {
  overflow:scroll;
}

It was a bit tricky, but there is the CSS.

An (x)HTML tag like this:

<textarea id="myTextarea" rows="10" cols="15"></textarea>

And at the end of the <head> section a JavaScript like this:

 window.onload=function(){
   document.getElementById("myTextarea").wrap='off';
 }

The JavaScript is for making the W3C validator passing XHTML 1.1 Strict, since the wrap attribute is not official and thus cannot be an (x)HTML tag directly, but most browsers handle it, so after loading the page it sets that attribute.

Hope this can be tested on more browsers and versions and help someone to improve it and makes it fully cross-browser for all versions.

How can I move a tag on a git branch to a different commit?

I try to avoid a few things when using Git.

  1. Using knowledge of the internals, e.g. refs/tags. I try to use solely the documented Git commands and avoid using things which require knowledge of the internal contents of the .git directory. (That is to say, I treat Git as a Git user and not a Git developer.)

  2. The use of force when not required.

  3. Overdoing things. (Pushing a branch and/or lots of tags, to get one tag where I want it.)

So here is my non-violent solution for changing a tag, both locally and remotely, without knowledge of the Git internals.

I use it when a software fix ultimately has a problem and needs to be updated/re-released.

git tag -d fix123                # delete the old local tag
git push github :fix123          # delete the old remote tag (use for each affected remote)
git tag fix123 790a621265        # create a new local tag
git push github fix123           # push new tag to remote    (use for each affected remote)

github is a sample remote name, fix123 is a sample tag name, and 790a621265 a sample commit.

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

I had the same problem. remove border-collapse entirely and use: cellspacing="0" cellpadding="0" in the html document. example:

<table class="top_container" align="center" cellspacing="0" cellpadding="0">

How to implement a Map with multiple keys?

If you intend to use combination of several keys as one, then perhaps apache commnons MultiKey is your friend. I don't think it would work one by one though..

Bootstrap 4 Center Vertical and Horizontal Alignment

From the doc (bootsrap 4):

https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

.justify-content-start
.justify-content-end
.justify-content-center
.justify-content-between
.justify-content-around
.justify-content-sm-start
.justify-content-sm-end
.justify-content-sm-center
.justify-content-sm-between
.justify-content-sm-around
.justify-content-md-start
.justify-content-md-end
.justify-content-md-center
.justify-content-md-between
.justify-content-md-around
.justify-content-lg-start
.justify-content-lg-end
.justify-content-lg-center
.justify-content-lg-between
.justify-content-lg-around
.justify-content-xl-start
.justify-content-xl-end
.justify-content-xl-center
.justify-content-xl-between
.justify-content-xl-around

Running Node.Js on Android

I just had a jaw-drop moment - Termux allows you to install NodeJS on an Android device!

It seems to work for a basic Websocket Speed Test I had on hand. The http served by it can be accessed both locally and on the network.

There is a medium post that explains the installation process

Basically: 1. Install termux 2. apt install nodejs 3. node it up!

One restriction I've run into - it seems the shared folders don't have the necessary permissions to install modules. It might just be a file permission thing. The private app storage works just fine.

Switching to a TabBar tab view programmatically?

My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:

tabBarController.selectedIndex = 2

However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:

override var shouldAutomaticallyForwardAppearanceMethods: Bool 
{
    return true
}

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

sudo psql --host=localhost --dbname=database-name --username=postgres

This solved my issue

PHP "pretty print" json_encode

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

This should do the job:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

See http://www.php.net/manual/en/function.json-encode.php

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)

What's the difference between HEAD, working tree and index, in Git?

Working tree

Your working tree are the files that you are currently working on.

Git index

  • The git "index" is where you place files you want commit to the git repository.

  • The index is also known as cache, directory cache, current directory cache, staging area, staged files.

  • Before you "commit" (checkin) files to the git repository, you need to first place the files in the git "index".

  • The index is not the working directory: you can type a command such as git status, and git will tell you what files in your working directory have been added to the git index (for example, by using the git add filename command).

  • The index is not the git repository: files in the git index are files that git would commit to the git repository if you used the git commit command.

basic authorization command for curl

One way, provide --user flag as part of curl, as follows:

curl --user username:password http://example.com

Another way is to get Base64 encoded token of "username:password" from any online website like - https://www.base64encode.org/ and pass it as Authorization header of curl as follows:

curl -i -H 'Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=' http://localhost:8080/

Here, dXNlcm5hbWU6cGFzc3dvcmQ= is Base64 encoded token of username:password.

Changing user agent on urllib2.urlopen

Another solution in urllib2 and Python 2.7:

req = urllib2.Request('http://www.example.com/')
req.add_unredirected_header('User-Agent', 'Custom User-Agent')
urllib2.urlopen(req)

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

How to open a new tab using Selenium WebDriver

Check this complete example to understand how to open multiple tabs and switch between the tabs and at the end close all tabs.

public class Tabs {

    WebDriver driver;

    Robot rb;

    @BeforeTest
    public void setup() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("http://qaautomated.com");
    }

    @Test
    public void openTab() {
        // Open tab 2 using CTRL + T keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

        // Open URL In 2nd tab.
        driver.get("http://www.qaautomated.com/p/contact.html");

        // Call switchToTab() method to switch to the first tab
        switchToTab();

        // Call switchToTab() method to switch to the second tab.
        switchToTab();
    }

    public void switchToTab() {
        // Switching between tabs using CTRL + tab keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

        // Switch to current selected tab's content.
        driver.switchTo().defaultContent();
    }

    @AfterTest
    public void closeTabs() throws AWTException {
        // Used Robot class to perform ALT + SPACE + 'c' keypress event.
        rb = new Robot();
        rb.keyPress(KeyEvent.VK_ALT);
        rb.keyPress(KeyEvent.VK_SPACE);
        rb.keyPress(KeyEvent.VK_C);
    }

}

This example is given by this web page.

Decreasing height of bootstrap 3.0 navbar

if you are using the less source, there should be a variable for the navbar height in the variables.less file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height

Best way to store a key=>value array in JavaScript?

In javascript a key value array is stored as an object. There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object?

Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown.

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.

Simple Array eg.

$(document).ready(function(){

    var countries = ['Canada','Us','France','Italy'];
    console.log('I am from '+countries[0]);
    $.each(countries, function(key, value) {
        console.log(key, value);
    });

});

Output -

0 "Canada"

1 "Us"

2 "France"

3 "Italy"

We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys.

Simple Object (json)

$(document).ready(function(){

    var person = {
        name: "James",
        occupation: "programmer",
        height: {
            feet: 6,
            inches: 1
        },
    }

    console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);

    $.each(person, function(key, value) {
        console.log(key, value);
    });

});

Output -

My name is James and I am a 6 ft 1 programmer

name James

occupation programmer

height Object {feet: 6, inches: 1}

In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person.

Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so -

JSON array (array of objects) -

$(document).ready(function(){

    var people = [
        {
            name: "James",
            occupation: "programmer",
            height: {
                feet: 6,
                inches: 1
            }
        }, {
            name: "Peter",
            occupation: "designer",
            height: {
                feet: 4,
                inches: 10
            }
        }, {
            name: "Joshua",
            occupation: "CEO",
            height: {
                feet: 5,
                inches: 11
            }
        }
    ];

    console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");

    $.each(people, function(key, person) {
        console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
    });

});

Output -

My name is Joshua and I am a 5 ft 11 CEO

My name is James and I am a 6 ft 1 programmer

My name is Peter and I am a 4 ft 10 designer

My name is Joshua and I am a 5 ft 11 CEO

Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied.

How to replace (or strip) an extension from a filename in Python?

As @jethro said, splitext is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must be the part of the filename coming after the final period:

filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'

The rsplit tells Python to perform the string splits starting from the right of the string, and the 1 says to perform at most one split (so that e.g. 'foo.bar.baz' -> [ 'foo.bar', 'baz' ]). Since rsplit will always return a non-empty array, we may safely index 0 into it to get the filename minus the extension.

Proper way to initialize a C# dictionary with values?

You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
    { 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
    { 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
    { 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};

See Microsoft Docs for details.

jquery input select all on focus

var timeOutSelect;
$("input[type=text]").focus(function() { 
        var save_this = $(this);
        clearTimeout(timeOutSelect);
        timeOutSelect = window.setTimeout (function(){ 
                save_this.select(); 
        }, 100);
});

Use clearTimeout for more security if you switch quickly between two input.. clearTimeout clean the old timeout...

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

SOLUTIONS

  1. Sometimes the project is created before installing g++. So install g++ first and then recreate your project. This worked for me.
  2. Paste the following line in CMakeCache.txt: CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++

Note the path to g++ depends on OS. I have used my fedora path obtained using which g++

Video auto play is not working in Safari and Chrome desktop browser

Angular 10:

<video [muted]="true" [autoplay]="true" [loop]="true">
    <source src="/assets/video.mp4" type="video/mp4"/>
</video>

Static Initialization Blocks

The non-static block:

{
    // Do Something...
}

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

Example:

public class Test {

    static{
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = new Test();
    }
}

This prints:

Static
Non-static block
Non-static block

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem, the annotation @Autowired in the test code did not work under using the Maven command line while it worked fine in Eclipse. I just update my JUnit version from 4.4 to 4.9 and the problem was solved.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.1</version>
</dependency>

Can I change the height of an image in CSS :before/:after pseudo-elements?

Nowadays with flexbox you can greatly simplify your code and only adjust 1 parameter as needed:

.pdflink:after {
    content: url('/images/pdf.png');
    display: inline-flex;
    width: 10px;
}

Now you can just adjust the width of the element and the height will automatically adjust, increase/decrease the width until the height of the element is at the number you need.

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

CURRENT_TIMESTAMP in milliseconds

I faced the same issue recently and I created a small github project that contains a new mysql function UNIX_TIMESTAMP_MS() that returns the current timestamp in milliseconds.

Also you can do the following :

SELECT UNIX_TIMESTAMP_MS(NOW(3)) or SELECT UNIX_TIMESTAMP_MS(DateTimeField)

The project is located here : https://github.com/silviucpp/unix_timestamp_ms

To compile you need to Just run make compile in the project root.

Then you need to only copy the shared library in the /usr/lib/mysql/plugin/ (or whatever the plugin folder is on your machine.)

After this just open a mysql console and run :

CREATE FUNCTION UNIX_TIMESTAMP_MS RETURNS INT SONAME 'unix_timestamp_ms.so';

I hope this will help, Silviu

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) 

Iterating through array - java

You can import the lib org.apache.commons.lang.ArrayUtils

There is a static method where you can pass in an int array and a value to check for.

contains(int[] array, int valueToFind) Checks if the value is in the given array.

ArrayUtils.contains(intArray, valueToFind);

ArrayUtils API

jQuery, get html of a whole element

You can achieve that with just one line code that simplify that:

$('#divs').get(0).outerHTML;

As simple as that.

java.util.regex - importance of Pattern.compile()?

Compile parses the regular expression and builds an in-memory representation. The overhead to compile is significant compared to a match. If you're using a pattern repeatedly it will gain some performance to cache the compiled pattern.

JPA 2.0, Criteria API, Subqueries, In Expressions

You can use double join, if table A B are connected only by table AB.

public static Specification<A> findB(String input) {
    return (Specification<A>) (root, cq, cb) -> {
        Join<A,AB> AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
        Join<AB,B> ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
        return cb.equal(ABjoinB.get(B_.NAME),input);
    };
}

That's just an another option
Sorry for that timing but I have came across this question and I also wanted to make SELECT IN but I didn't even thought about double join. I hope it will help someone.

Credit card expiration dates - Inclusive or exclusive?

lots of big companies dont even use your expiration date anymore because it causes auto-renewal of payments to be lost when cards are issued with new expiration dates and the same account number. This has been a huge problem in the service industry, so these companies have cornered the card issuers into processing payments w/o expiration dates to avoid this pitfall. Not many people know about this yet, so not all companies use this practice.

How to compare strings in sql ignoring case?

SELECT STRCMP("string1", "string2");

this returns 0 if the strings are equal.

  • If string1 = string2, this function returns 0 (ignoring the case)
  • If string1 < string2, this function returns -1
  • If string1 > string2, this function returns 1

https://www.w3schools.com/sql/func_mysql_strcmp.asp

How do I revert all local changes in Git managed project to previous state?

I searched for a similar issue,

Wanted to throw away local commits:

  1. cloned the repository (git clone)
  2. switched to dev branch (git checkout dev)
  3. did few commits (git commit -m "commit 1")
  4. but decided to throw away these local commits to go back to remote (origin/dev)

So did the below:

git reset --hard origin/dev

Check:

git status  

        On branch dev  
        Your branch is up-to-date with 'origin/dev'.  
        nothing to commit, working tree clean  

now local commits are lost, back to the initial cloned state, point 1 above.

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

The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.

That's what content negotiation is for.

  • The HTML specification doesn't specify any image formats for the <img> element.
  • The HTML specification doesn't specify any style sheet languages for the <style> element.
  • The HTML specification doesn't specify any scripting languages for the <script> element.
  • The HTML specification doesn't specify any object formats for the <object> and embed elements.
  • The HTML specification doesn't specify any audio formats for the <audio> element.

Why should it specify one for the <video> element?

How can one display images side by side in a GitHub README.md?

The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.

To your specific example it would look something like this:

Solarized dark             |  Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png)  |  ![](https://...Ocean.png)

This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the ... with the real link. The :s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.

Execute function after Ajax call is complete

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function

How can I view the contents of an ElasticSearch index?

You can even add the size of the terms (indexed terms). Have a look at Elastic Search: how to see the indexed data

Automating running command on Linux from Windows using PuTTY

You can do both tasks (the upload and the command execution) using WinSCP. Use WinSCP script like:

option batch abort
option confirm off
open your_session
put %1%
call script.sh
exit

Reference for the call command:
https://winscp.net/eng/docs/scriptcommand_call

Reference for the %1% syntax:
https://winscp.net/eng/docs/scripting#syntax

You can then run the script like:

winscp.exe /console /script=script_path\upload.txt /parameter file_to_upload.dat

Actually, you can put a shortcut to the above command to the Windows Explorer's Send To menu, so that you can then just right-click any file and go to the Send To > Upload using WinSCP and Execute Remote Command (=name of the shortcut).

For that, go to the folder %USERPROFILE%\SendTo and create a shortcut with the following target:

winscp_path\winscp.exe /console /script=script_path\upload.txt /parameter %1

See Creating entry in Explorer's "Send To" menu.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

npm check and update package if needed

To check if any module in a project is 'old':

npm outdated

'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.

For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:

[email protected] node_modules/xml2js current=0.2.6

To update all dependencies, if you are confident this is desirable:

npm update

Or, to update a single dependency such as xml2js:

npm update xml2js

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I had this error and found the reason for the error in my case. I'm still answering to this old post because it ranks pretty high on Google.

The variables of both of the column I wanted to link were integers but one of the ints had 'unsigned' checked on. Simply un-checking that fixed my error.

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

Assume LMN2011* files are inside /home/me but skipping anything in /home/me/temp or below:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'

How to update a pull request from forked repo?

You have done it correctly. The pull request will automatically update. The process is:

  1. Open pull request
  2. Commit changes based on feedback in your local repo
  3. Push to the relevant branch of your fork

The pull request will automatically add the new commits at the bottom of the pull request discussion (ie, it's already there, scroll down!)

Angular cli generate a service and include the provider in one step

slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0

ng g service backendApi --module=app.module

get url content PHP

Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.

Mock functions in Go

I would do something like,

Main

var getPage = get_page
func get_page (...

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := getPage(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}

Test

func TestDownloader (t *testing.T) {
    origGetPage := getPage
    getPage = mock_get_page
    defer func() {getPage = origGatePage}()
    // The rest to be written
}

// define mock_get_page and rest of the codes
func mock_get_page (....

And I would avoid _ in golang. Better use camelCase

How to make an alert dialog fill 90% of screen size?

Well, you have to set your dialog's height and width before to show this ( dialog.show() )

so, do something like this:

dialog.getWindow().setLayout(width, height);

//then

dialog.show()

Getting this code, i made it some changes:

dialog.getWindow().setLayout((int)(MapGeaGtaxiActivity.this.getWindow().peekDecorView().getWidth()*0.9),(int) (MapGeaGtaxiActivity.this.getWindow().peekDecorView().getHeight()*0.9));

however, dialog size's could change when the device change its position. Perhaps you need to handle by your own when metrics changes. PD: peekDecorView, implies that layout in activity is properly initialized otherwise you may use

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;

in order to get screen size

How do I rename a local Git branch?

Another option is not to use the command line at all. Git GUI clients such as SourceTree take away much of the syntactical learning curve / pain that causes questions such as this one to be amongst the most viewed on Stack Overflow.

In SourceTree, right click on any local branch in the "Branches" pane on the left and select "Rename ...".

Create a .csv file with values from a Python list

Here is working copy-paste example for Python 3.x with options to define your own delimiter and quote char.

import csv

mylist = ['value 1', 'value 2', 'value 3']

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
    employee_writer.writerow(mylist)

This will generate employee_file.csv that looks like this:

"value 1","value 2","value 3"

NOTE:

If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote fields only if they contain the delimiter or the quotechar. This is the default case.

If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all fields.

If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields containing text data and convert all numeric fields to the float data type.

If quoting is set to csv.QUOTE_NONE, then .writerow() will escape delimiters instead of quoting them. In this case, you also must provide a value for the escapechar optional parameter.

Const in JavaScript: when to use it and is it necessary?

It provides:

  1. a constant reference, eg const x = [] - the array can be modified, but x can't point to another array; and

  2. block scoping.

const and let will together replace var in ecma6/2015. See discussion at https://strongloop.com/strongblog/es6-variable-declarations/

How can I update the current line in a C# Windows Console App?

\r is used for these scenarios.
\r represents a carriage return which means the cursor returns to the start of the line.
That's why Windows uses \n\r as its new line marker.
\n moves you down a line, and \r returns you to the start of the line.

How to install sshpass on mac?

Some years have passed and there is now a proper Homebrew Tap for sshpass, maintained by Aleks Hudochenkov. To install sshpass from this tap, run:

brew install hudochenkov/sshpass/sshpass

Angular JS update input field after change

You can add ng-change directive to input fields. Have a look at the docs example.

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

An attempt was made to access a socket in a way forbidden by its access permissions

If You need to access SQL server on hostgator remotely using SSMS, you need to white list your IP in hostgator. Usually it takes 1 hour to open port for the whitelisted IP

HTML SELECT - Change selected option by VALUE using JavaScript

If you are using jQuery:

$('#sel').val('bike');

Jquery - animate height toggle

Worked for me:

$(".filter-mobile").click(function() {
   if ($("#menuProdutos").height() > 0) {
      $("#menuProdutos").animate({
         height: 0
      }, 200);
   } else {
      $("#menuProdutos").animate({
         height: 500
      }, 200);
   }
});

Including external HTML file to another HTML file

Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.

<object data="html/stuff_to_include.html"> 
    Your browser doesn’t support the object tag. 
</object>

more info at http://www.w3schools.com/tags/tag_object.asp

How can I check if a user is logged-in in php?

See this script for registering. It is simple and very easy to understand.

<?php
    define('DB_HOST', 'Your Host[Could be localhost or also a website]');
    define('DB_NAME', 'database name');
    define('DB_USERNAME', 'Username[In many cases root, but some sites offer a MySQL page where the username might be different]');
    define('DB_PASSWORD', 'whatever you keep[if username is root then 99% of the password is blank]');

    $link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);

    if (!$link) {
        die('Could not connect line 9');
    }

    $DB_SELECT = mysql_select_db(DB_NAME, $link);

    if (!$DB_SELECT) {
        die('Could not connect line 15');
    }

    $valueone = $_POST['name'];
    $valuetwo = $_POST['last_name'];
    $valuethree = $_POST['email'];
    $valuefour = $_POST['password'];
    $valuefive = $_POST['age'];

    $sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";

    if (!mysql_query($sqlone)) {
        die('Could not connect name line 33');
    }

    mysql_close();
?>

Make sure you make all the database stuff using phpMyAdmin. It's a very easy tool to work with. You can find it here: phpMyAdmin

How to open every file in a folder

I was looking for this answer:

import os,glob
folder_path = '/some/path/to/file'
for filename in glob.glob(os.path.join(folder_path, '*.htm')):
  with open(filename, 'r') as f:
    text = f.read()
    print (filename)
    print (len(text))

you can choose as well '*.txt' or other ends of your filename

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

You like to set charset and unescaped unicode

 header('Content-Type: application/json;charset=utf-8');  
 json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

MySQL combine two columns and add into a new column

Create the column:

ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);

Update the current values:

UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);

Update all future values automatically:

CREATE TRIGGER insert_trigger
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

CREATE TRIGGER update_trigger
BEFORE UPDATE ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

How to concatenate two layers in keras?

You're getting the error because result defined as Sequential() is just a container for the model and you have not defined an input for it.

Given what you're trying to build set result to take the third input x3.

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))

# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])

# then concatenate the two outputs

result = Concatenate([merged,  third])

ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)

result.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

However, my preferred way of building a model that has this type of input structure would be to use the functional api.

Here is an implementation of your requirements to get you started:

from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad

first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)

second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)

merge_one = concatenate([first_dense, second_dense])

third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])

model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

To answer the question in the comments:

  1. How are result and merged connected? Assuming you mean how are they concatenated.

Concatenation works like this:

  a        b         c
a b c   g h i    a b c g h i
d e f   j k l    d e f j k l

i.e rows are just joined.

  1. Now, x1 is input to first, x2 is input into second and x3 input into third.

Have a fixed position div that needs to scroll if content overflows

Leaving an answer for anyone looking to do something similar but in a horizontal direction, like I wanted to.

Tweaking @strider820's answer like below will do the magic:

.fixed-content {        //comments showing what I replaced.
    left:0;             //top: 0;
    right:0;            //bottom:0;
    position:fixed;
    overflow-y:hidden;  //overflow-y:scroll;
    overflow-x:auto;    //overflow-x:hidden;
}

That's it. Also check this comment where @train explained using overflow:auto over overflow:scroll.

Eclipse JPA Project Change Event Handler (waiting)

Don't know why, my Neon Eclipse still having this issue, it doesn't seem to be fixed in Mars version as many people said.

I found that using command is too troublesome, I delete the plugin away via the Eclipse Installation Manager.

Neon: [Help > Installation Details > Installed Software]

Oxygen: [Preferences > Install/Update > Installed Software]

Just select the plugin "Dali Java Persistence Tools -JPA Support" and click "uninstall" will do. Please take note my screen below doesn't have that because I already uninstalled.

enter image description here

How to get address of a pointer in c/c++?

You can use %p in C

In C:

printf("%p",p)

In C++:

cout<<"Address of pointer p is: "<<p

How to clear https proxy setting of NPM?

If you go through the npm config documentation, it says:

proxy

Default: HTTP_PROXY or http_proxy environment variable, or null

Type: url

As per this, to disable usage of proxy, proxy setting must be set to null. To set proxy value to null, one has to make sure that HTTP_PROXY or http_proxy environment variable is not set. So unset these environment variables and make sure that npm config ls -l shows proxy = null.

Also, it is important to note that:

  • Deleting http_proxy and https_proxy config settings alone will not help if you still have HTTP_PROXY or http_proxy environment variable is set to something and
  • Setting registry to use http:// and setting strict-ssl to false will not help you if you are not behind a proxy anyway and have HTTP_PROXY set to something.

It would have been better if npm had made the type of proxy setting to boolean to switch on/off the proxy usage. Or, they can introduce a new setting of sort use_proxy of type boolean.

Check if file is already open

(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)

This whole issue is fraught with portability issues and race conditions:

  • You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
  • It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
  • Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.

A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.

Notes:

  1. If you use the Files API instead of the File API you will get more information in the event of a failure.

  2. On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.

Pass Multiple Parameters to jQuery ajax call

simply add as many properties as you need to the data object.

 $.ajax({
                    type: "POST",
                    url: "popup.aspx/GetJewellerAssets",
                    contentType: "application/json; charset=utf-8",
                    data: {jewellerId: filter , foo: "bar", other: "otherValue"},
                    dataType: "json",
                    success: AjaxSucceeded,
                    error: AjaxFailed
                });

How do I find a list of Homebrew's installable packages?

brew help will show you the list of commands that are available.

brew list will show you the list of installed packages. You can also append formulae, for example brew list postgres will tell you of files installed by postgres (providing it is indeed installed).

brew search <search term> will list the possible packages that you can install. brew search post will return multiple packages that are available to install that have post in their name.

brew info <package name> will display some basic information about the package in question.

You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)

How do getters and setters work?

1. The best getters / setters are smart.

Here's a javascript example from mozilla:

var o = { a:0 } // `o` is now a basic object

Object.defineProperty(o, "b", { 
    get: function () { 
        return this.a + 1; 
    } 
});

console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)

I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.

2. Getters / setters in php

Example from sof

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

citings:

Can I pass a JavaScript variable to another browser window?

Yes, scripts can access properties of other windows in the same domain that they have a handle on (typically gained through window.open/opener and window.frames/parent). It is usually more manageable to call functions defined on the other window rather than fiddle with variables directly.

However, windows can die or move on, and browsers deal with it differently when they do. Check that a window (a) is still open (!window.closed) and (b) has the function you expect available, before you try to call it.

Simple values like strings are fine, but generally it isn't a good idea to pass complex objects such as functions, DOM elements and closures between windows. If a child window stores an object from its opener, then the opener closes, that object can become 'dead' (in some browsers such as IE), or cause a memory leak. Weird errors can ensue.

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

jQuery ui dialog change title after load-callback

I have found simpler solution:

$('#clickToCreate').live('click', function() {
     $('#yourDialogId')
         .dialog({
              title: "Set the title to Create"
         })
         .dialog('open'); 
});


$('#clickToEdit').live('click', function() {
     $('#yourDialogId')
         .dialog({
              title: "Set the title To Edit"
         })
         .dialog('open'); 
});

Hope that helps!

ESLint - "window" is not defined. How to allow global variables in package.json

There is a builtin environment: browser that includes window.

Example .eslintrc.json:

"env": {
    "browser": true,
    "node": true,
    "jasmine": true
  },

More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments

Also see the package.json answer by chevin99 below.

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Keylistener in Javascript

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

css label width not taking effect

label's default display mode is inline, which means it automatically sizes itself to it's content. To set a width you'll need to set display:block and then do some faffing to get it positioned correctly (probably involving float)

How do I truncate a .NET string?

Just in case there's not enough answers here, here's mine :)

public static string Truncate(this string str, 
                              int totalLength, 
                              string truncationIndicator = "")
{
    if (string.IsNullOrEmpty(str) || str.Length < totalLength) 
        return str;

    return str.Substring(0, totalLength - truncationIndicator.Length) 
           + truncationIndicator;
}

to use:

"I use it like this".Truncate(5,"~")

Zoom in on a point (using scale and translate)

Here's an approach I use for tighter control over how things are drawn

_x000D_
_x000D_
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var scale = 1;
var xO = 0;
var yO = 0;

draw();

function draw(){
    // Clear screen
    ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);

    // Original coordinates
    const xData = 50, yData = 50, wData = 100, hData = 100;
    
    // Transformed coordinates
    const x = xData * scale + xO,
     y = yData * scale + yO,
     w = wData * scale,
     h = hData * scale;

    // Draw transformed positions
    ctx.fillStyle = "black";
    ctx.fillRect(x,y,w,h);
}

canvas.onwheel = function (e){
    e.preventDefault();

    const r = canvas.getBoundingClientRect(),
      xNode =  e.pageX - r.left,
      yNode =  e.pageY - r.top;

    const newScale = scale * Math.exp(-Math.sign(e.deltaY) * 0.2),
      scaleFactor = newScale/scale;

    xO = xNode - scaleFactor * (xNode - xO);
    yO = yNode - scaleFactor * (yNode - yO);
    scale = newScale;

    draw();
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
_x000D_
_x000D_

How do I read the file content from the Internal storage - Android App

For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

JSLint is suddenly reporting: Use the function form of "use strict"

Add a file .jslintrc (or .jshintrc in the case of jshint) at the root of your project with the following content:

{
    "node": true
}

DropDownList in MVC 4 with Razor

_x000D_
_x000D_
List<tblstatu> status = new List<tblstatu>();_x000D_
            status = psobj.getstatus();_x000D_
            model.statuslist = status;_x000D_
            model.statusid = status.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.StatusId.ToString(),_x000D_
                Text = x.StatusName_x000D_
            });_x000D_
_x000D_
_x000D_
  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
_x000D_
_x000D_
_x000D_

Android Center text on canvas

Add these to your onDraw method:

paint.setColor(getContext().getResources().getColor(R.color.black));
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Text", (float) getHeight() / 2f, (float) getWidth() / 2f, paint);

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

convert iso date to milliseconds in javascript

if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

It appears that SSRS has an issue(at leastin version 2008) - I'm studying this website that explains it

Where it says if you have two columns(from 2 diff. tables) with the same name, then it'll cause that problem.

From source:

SELECT a.Field1, a.Field2, a.Field3, b.Field1, b.field99 FROM TableA a JOIN TableB b on a.Field1 = b.Field1

SQL handled it just fine, since I had prefixed each with an alias (table) name. But SSRS uses only the column name as the key, not table + column, so it was choking.

The fix was easy, either rename the second column, i.e. b.Field1 AS Field01 or just omit the field all together, which is what I did.

Disable scrolling in webview?

This should be the complete answer. As suggested by @GDanger . Extend WebView to override the scroll methods and embed the custom webview within layout xml.

public class ScrollDisabledWebView extends WebView {

    private boolean scrollEnabled = false;

    public ScrollDisabledWebView(Context context) {
        super(context);
        initView(context);
    }

    public ScrollDisabledWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initView(context);
    }
    // this is important. Otherwise it throws Binary Inflate Exception.
    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY,
                                   int scrollRangeX, int scrollRangeY, int maxOverScrollX,
                                   int maxOverScrollY, boolean isTouchEvent) {
        if (scrollEnabled) {
            return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
                    scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
        }
        return false;
    }

    @Override
    public void scrollTo(int x, int y) {
        if (scrollEnabled) {
            super.scrollTo(x, y);
        }
    }

    @Override
    public void computeScroll() {
        if (scrollEnabled) {
            super.computeScroll();
        }
    }
}

And then embed in layout file as follows

<com.sample.apps.ScrollDisabledWebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    tools:context="com.sample.apps.HomeActivity"/>

Then in the Activity, use some additional methods for disabling scrollbars too.

ScrollDisabledWebView webView = (ScrollDisabledWebView) findViewById(R.id.webView);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

Adding a collaborator to my free GitHub account?

It is pretty easy to add a collaborator to a free plan.

  1. Navigate to the repository on Github you wish to share with your collaborator.
  2. Click on the "Settings" tab on the right side of the menu at the top of the screen.
  3. On the new page, click the "Collaborators" menu item on the left side of the page.
  4. Start typing the new collaborator's GitHub username into the text box.
  5. Select the GitHub user from the list that appears below the text box.
  6. Click the "Add" button.

The added user should now be able to push to your repository on GitHub.

How to append text to an existing file in Java?

FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

Then catch an IOException somewhere upstream.

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

How to add items to a combobox in a form in excel VBA?

Here is another answer:

With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With 

Source: Show the

Getting the class of the element that fired an event using JQuery

If you are using jQuery 1.7:

alert($(this).prop("class"));

or:

alert($(event.target).prop("class"));

jquery : focus to div is not working

Focus doesn't work on divs by default. But, according to this, you can make it work:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

http://api.jquery.com/focus/

How to achieve function overloading in C?

Here is the clearest and most concise example I've found demonstrating function overloading in C:

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

int addi(int a, int b) {
    return a + b;
}

char *adds(char *a, char *b) {
    char *res = malloc(strlen(a) + strlen(b) + 1);
    strcpy(res, a);
    strcat(res, b);
    return res;
}

#define add(a, b) _Generic(a, int: addi, char*: adds)(a, b)

int main(void) {
    int a = 1, b = 2;
    printf("%d\n", add(a, b)); // 3

    char *c = "hello ", *d = "world";
    printf("%s\n", add(c, d)); // hello world

    return 0;
}

https://gist.github.com/barosl/e0af4a92b2b8cabd05a7

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Stoping and starting the mysql server from terminal resolved my issue. Below are the cmds to stop and start the mysql server in MacOs.

sudo /usr/local/mysql/support-files/mysql.server stop
sudo /usr/local/mysql/support-files/mysql.server start

Note: Restarting the services from Mac System preference didn't resolve the issue in my mac. So try to restart from terminal.

What is the difference between float and double?

Type float, 32 bits long, has a precision of 7 digits. While it may store values with very large or very small range (+/- 3.4 * 10^38 or * 10^-38), it has only 7 significant digits.

Type double, 64 bits long, has a bigger range (*10^+/-308) and 15 digits precision.

Type long double is nominally 80 bits, though a given compiler/OS pairing may store it as 12-16 bytes for alignment purposes. The long double has an exponent that just ridiculously huge and should have 19 digits precision. Microsoft, in their infinite wisdom, limits long double to 8 bytes, the same as plain double.

Generally speaking, just use type double when you need a floating point value/variable. Literal floating point values used in expressions will be treated as doubles by default, and most of the math functions that return floating point values return doubles. You'll save yourself many headaches and typecastings if you just use double.

Can I run a 64-bit VMware image on a 32-bit machine?

If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

The error is caused by the number of class dependencies you have in your app Gradle file. If the classes exceed 72,400, you might want to use multidex as a solution to better handle file indexing. Findout more from here: https://developer.android.com/studio/build/multidex

Convert special characters to HTML in Javascript

If you need support for all standardized named character references, unicode and ambiguous ampersands, the he library is the only 100% reliable solution I'm aware of!


Example use

he.encode('foo © bar ? baz  qux'); 
// Output : 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'

he.decode('foo &copy; bar &ne; baz &#x1D306; qux');
// Output : 'foo © bar ? baz  qux'

How to make a window always stay on top in .Net?

The way i solved this was by making a system tray icon that had a cancel option.

How do I pass multiple parameters in Objective-C?

Objective-C doesn't have named parameters, so everything on the left side of a colon is part of the method name. For example,

getBusStops: forTime:

is the name of the method. The name is broken up so it can be more descriptive. You could simply name your method

getBusStops: :

but that doesn't tell you much about the second parameter.

How to solve java.lang.OutOfMemoryError trouble in Android

I see only two options:

  1. You have memory leaks in your application.
  2. Devices do not have enough memory when running your application.

Get the value for a listbox item by index

This works for me:

ListBox x = new ListBox();
x.Items.Add(new ListItem("Hello", "1"));
x.Items.Add(new ListItem("Bye", "2"));

Console.Write(x.Items[0].Value);

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

How to refresh materialized view in oracle

If you're working with SQL Developer, you have to put the dbms_view in lowercase. The rest compiled fine for me although I haven't called the procedure from code yet.

CREATE OR REPLACE PROCEDURE "MAT_VIEW_FOO_TBL" AS 
BEGIN
  dbms_mview.refresh('v_materialized_foo_tbl');
END;

How to set up a PostgreSQL database in Django

Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this:

$ sudo apt-get install libpq-dev

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

TLS 1.2 not working in cURL

Replace following

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');

With

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

Should work flawlessly.

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN
IF THEN ELSE
IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

So your code should appear like this.

    declare
        var_number number;
    begin
        var_number := 10;
        if var_number > 100 then
           dbms_output.put_line(var_number ||' is greater than 100');
--elseif should be replaced with elsif
        elsif var_number < 100 then
           dbms_output.put_line(var_number ||' is less than 100');
        else
           dbms_output.put_line(var_number ||' is equal to 100');
        end if;
    end; 

Adding Google Play services version to your app's manifest?

This error can also happen when you've downloaded a new version of Google Play Services and not installed the latest SDK. Thats what happened to me. So, as the others mentioned, if you try to import Google Play Services and then open the console, you'll see a compile error. Try installing all the recent Android SDKs and try again, if this is the case.

Vue is not defined

Sometimes the problem may be if you import that like this:

const Vue = window.vue;

this may overwrite the original Vue reference.

jQuery: How to detect window width on the fly?

Put your if condition inside resize function:

var windowsize = $(window).width();

$(window).resize(function() {
  windowsize = $(window).width();
  if (windowsize > 440) {
    //if the window is greater than 440px wide then turn on jScrollPane..
      $('#pane1').jScrollPane({
         scrollbarWidth:15, 
         scrollbarMargin:52
      });
  }
});

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

How do I grep recursively?

grep -r "texthere" .

The first parameter represents the regular expression to search for, while the second one represents the directory that should be searched. In this case, . means the current directory.

Note: This works for GNU grep, and on some platforms like Solaris you must specifically use GNU grep as opposed to legacy implementation. For Solaris this is the ggrep command.

Function to convert column number to letter?

Here, a simple function in Pascal (Delphi).

function GetColLetterFromNum(Sheet : Variant; Col : Integer) : String;
begin
  Result := Sheet.Columns[Col].Address;  // from Col=100 --> '$CV:$CV'
  Result := Copy(Result, 2, Pos(':', Result) - 2);
end;

Best way to check if an PowerShell Object exist?

Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System.Object] will be true for any possible non-null value. (In all cases, it will be false for any null-value.)

My value is nothing if not an object.

Assign format of DateTime with data annotations?

That works for me

[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

How to find a hash key containing a matching value

Another approach I would try is by using #map

clients.map{ |key, _| key if clients[key] == {"client_id"=>"2180"} }.compact 
#=> ["orange"]

This will return all occurences of given value. The underscore means that we don't need key's value to be carried around so that way it's not being assigned to a variable. The array will contain nils if the values doesn't match - that's why I put #compact at the end.

Android ViewPager with bottom dots

If anyone wants to build a viewPager with thumbnails as indicators, using this library could be an option: ThumbIndicator for viewPager that works also with image links as resources.

What's an Aggregate Root?

From Evans DDD:

An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single, specific ENTITY contained in the AGGREGATE.

And:

The root is the only member of the AGGREGATE that outside objects are allowed to hold references to[.]

This means that aggregate roots are the only objects that can be loaded from a repository.

An example is a model containing a Customer entity and an Address entity. We would never access an Address entity directly from the model as it does not make sense without the context of an associated Customer. So we could say that Customer and Address together form an aggregate and that Customer is an aggregate root.

Redirect Windows cmd stdout and stderr to a single file

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1

Using pointer to char array, values in that array can be accessed?

Your should create ptr as follows:

char *ptr;

You have created ptr as an array of pointers to chars. The above creates a single pointer to a char.

Edit: complete code should be:

char *ptr;
char arr[5] = {'a','b','c','d','e'};
ptr = arr;
printf("\nvalue:%c", *(ptr+0));

How do you echo a 4-digit Unicode character in Bash?

Here is a list of all unicode emoji's available:

https://en.wikipedia.org/wiki/Emoji#Unicode_blocks

Example:

echo -e "\U1F304"

For get the ASCII value of this character use hexdump

echo -e "" | hexdump -C

00000000  f0 9f 8c 84 0a                                    |.....|
00000005

And then use the values informed in hex format

echo -e "\xF0\x9F\x8C\x84\x0A"

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

@CookieValue(value="abc",required=true) String m

when I changed required from true to false,it worked out.

Java ArrayList for integers

you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

TypeError: Image data can not convert to float

try

import skimage
import random
from random import randint
import numpy as np
import matplotlib.pyplot as plt


xrow = raw_input("Enter the number of rows to be present in image.=>")
row = int(xrow)
ycolumn = raw_input("Enter the number of columns to be present in image.=>")
column = int(ycolumn)

A = np.zeros((row,column))
for x in xrange(1, row):
    for y in xrange(1, column):
        a = randint(0, 65535)
        A[x, y] = a

plt.imshow(A)
plt.show()

Javascript how to parse JSON array

"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied by a Ext.data.proxy.Proxy (in this case Ext.data.proxy.Ajax) furnished with a Ext.data.reader.Json (for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writers of several kinds.

Here's an example of a setup like that:

    var store = Ext.create('Ext.data.Store', {
        fields: [
            'counter_name',
            'counter_type',
            'counter_unit'
        ],

        proxy: {
            type: 'ajax',
            url: 'data1.json',

            reader: {
                type: 'json',
                idProperty: 'counter_name',
                rootProperty: 'counters'
            }
        }
    });

data1.json in this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name' is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters' specifies which property contains array of data items.

With a store setup this way you can re-read data from the server by calling store.load(). You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.

How do I limit the number of decimals printed for a double?

Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.

 private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;

 public static void main(String[] args)
  {
   computeShippingCost();
  }

  public static void computeShippingCost()
  {
   System.out.print("Enter a number of jars: ");
   Scanner kboard = new Scanner (System.in);
   nJars = kboard.nextInt();
   int nCartons = (nJars + 11) / 12;
   int totalOunces = (nJars * 21) + (nCartons * 25);
   int lbs = totalOunces / 16;


   double shippingCost =  ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;

     Formatter fmt = new Formatter();
     fmt.format("%.2f", shippingCost);

   System.out.print("$" + fmt);

   fmt.close();

}

How to get a float result by dividing two integer values using T-SQL?

The suggestions from stb and xiowl are fine if you're looking for a constant. If you need to use existing fields or parameters which are integers, you can cast them to be floats first:

SELECT CAST(1 AS float) / CAST(3 AS float)

or

SELECT CAST(MyIntField1 AS float) / CAST(MyIntField2 AS float)

Why em instead of px?

There is a simple solution if you want to use px to specify font size, but still want the usability that em's provide by placing this in your CSS file:

body {
  font-size: 62.5%;
}

Now specify you p (and other) tags like this:

p {
  font-size: 0.8em; /* This is equal to 8px */
  font-size: 1.0em; /* This is equal to 10px */
  font-size: 1.2em; /* This is equal to 12px */
  font-size: 2.0em; /* This is equal to 20px */
}

And so on.

True and False for && logic and || Logic table

Truth values can be described using a Boolean algebra. The article also contains tables for and and or. This should help you to get started or to get even more confused.

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

ActionBarActivity: cannot be resolved to a type

This way work for me with Eclipse in Android developer tool from Google -righ click - property - java build path - add external JAR

point to: android-support-v7-appcompat.jar in /sdk/extras/android/support/v7/appcompat/libs

Then

import android.support.v7.app.ActionBarActivity;

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

CSS3 animate border color

You can try this also...

_x000D_
_x000D_
button {
  background: none;
  border: 0;
  box-sizing: border-box;
  margin: 1em;
  padding: 1em 2em;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  vertical-align: middle;
  position: relative;
}
button::before, button::after {
  box-sizing: inherit;
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
}

.draw {
  -webkit-transition: color 0.25s;
  transition: color 0.25s;
}
.draw::before, .draw::after {
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
}
.draw::after {
  bottom: 0;
  right: 0;
}
.draw:hover {
  color: #60daaa;
}
.draw:hover::before, .draw:hover::after {
  width: 100%;
  height: 100%;
}
.draw:hover::before {
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  -webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
  transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
}
.draw:hover::after {
  border-bottom-color: #60daaa;
  border-left-color: #60daaa;
  -webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
  transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
}
_x000D_
<section class="buttons">
  <button class="draw">Draw</button>
</section>
_x000D_
_x000D_
_x000D_

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

How to remove td border with html?

<table border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <table border="0">
                <tr>
                    <td>one</td>
                    <td>two</td>
                </tr>
                <tr>
                    <td>one</td>
                </tr>
            </table>
        </td>
    </tr>
</table>

How should I use try-with-resources with JDBC?

Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:

try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
    PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
    try {
        PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
        s.setInt(1, userid);
        return s;
    } catch (SQLException e) { throw new RuntimeException(e); }
    }).get();
    ResultSet resultSet = stmt.executeQuery()) {
}

How to search a list of tuples in Python

[i for i, v in enumerate(L) if v[0] == 53]

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

How to block calls in android

OMG!!! YES, WE CAN DO THAT!!! I was going to kill myself after severe 24 hours of investigating and discovering... But I've found "fresh" solution!

// "cheat" with Java reflection to gain access to TelephonyManager's
// ITelephony getter
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony)m.invoke(tm);

all all all of hundreds of people who wants to develop their call-control software visit this start point

there is a project. and there are important comments (and credits)

briefly: copy aidl file, add permissions to manifest, copy-paste source for telephony management )))

Some more info for you. AT commands you can send only if you are rooted. Than you can kill system process and send commands but you will need a reboot to allow your phone to receive and send calls =)))

I'm very hapy =) Now my Shake2MuteCall will get an update !

Styling HTML5 input type number

Also you can replace size attribute by a style attribute:
<input type="number" name="numericInput" style="width: 50px;" min="0" max="18" value="0" />

How to resize an Image C#

Use below function with below example for changing image size :

//Example : 
System.Net.Mime.MediaTypeNames.Image newImage = System.Net.Mime.MediaTypeNames.Image.FromFile("SampImag.jpg");
System.Net.Mime.MediaTypeNames.Image temImag = FormatImage(newImage, 100, 100);

//image size modification unction   
public static System.Net.Mime.MediaTypeNames.Image FormatImage(System.Net.Mime.MediaTypeNames.Image img, int outputWidth, int outputHeight)
{

    Bitmap outputImage = null;
    Graphics graphics = null;
    try
    {
         outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
         graphics = Graphics.FromImage(outputImage);
         graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight),
         new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

         return outputImage;
     }
     catch (Exception ex)
     {
           return img;
     }
}

Passing variables in remote ssh command

Escape the variable in order to access variables outside of the ssh session: ssh [email protected] "~/tools/myScript.pl \$BUILD_NUMBER"

How to get GET (query string) variables in Express.js on Node.js?

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured domains and ssl. so these two lines would change:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

Push origin master error on new repository

i fixed my problem....

not sure what the problem was but using the gitx interface to commit my staged files, then...

$ git push origin master

worked...

i am having the same problem...

created a new folder added in the bort template files...

$ git commit -m 'first commit'

$ git remote add origin [email protected]:eltonstewart/band-of-strangers.git

$ git push origin master

then i get the same error...

error: src refspec master does not match any.
fatal: The remote end hung up unexpectedly
error: failed to push some refs to '[email protected]:eltonstewart/band-of-strangers.git'

How to exit a 'git status' list in a terminal?

Please try this steps in git bash, It may help you.

  1. CTRL + C
  2. :qa!

How to get a list of current open windows/process with Java?

YAJSW (Yet Another Java Service Wrapper) looks like it has JNA-based implementations of its org.rzo.yajsw.os.TaskList interface for win32, linux, bsd and solaris and is under an LGPL license. I haven't tried calling this code directly, but YAJSW works really well when I've used it in the past, so you shouldn't have too many worries.

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

How can I check the extension of a file?

os.path provides many functions for manipulating paths/filenames. (docs)

os.path.splitext takes a path and splits the file extension from the end of it.

import os

filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]

for fp in filepaths:
    # Split the extension from the path and normalise it to lowercase.
    ext = os.path.splitext(fp)[-1].lower()

    # Now we can simply use == to check for equality, no need for wildcards.
    if ext == ".mp3":
        print fp, "is an mp3!"
    elif ext == ".flac":
        print fp, "is a flac file!"
    else:
        print fp, "is an unknown file format."

Gives:

/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!

Rotate an image in image source in html

If your rotation angles are fairly uniform, you can use CSS:

<img id="image_canv" src="/image.png" class="rotate90">

CSS:

.rotate90 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:

<img id="image_canv" src="/image.png" data-rotate="90">

Sample jQuery:

$('img').each(function() {
    var deg = $(this).data('rotate') || 0;
    var rotate = 'rotate(' + deg + 'deg)';
    $(this).css({ 
        '-webkit-transform': rotate,
        '-moz-transform': rotate,
        '-o-transform': rotate,
        '-ms-transform': rotate,
        'transform': rotate 
    });
});

Demo:

http://jsfiddle.net/verashn/6rRnd/5/

How to trigger a file download when clicking an HTML button or JavaScript

What about:

<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">

Eclipse: stop code from running (java)

For Eclipse: menu bar-> window -> show view then find "debug" option if not in list then select other ...

new window will open and then search using keyword "debug" -> select debug from list

it will added near console tab. use debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)