Programs & Examples On #Execute

In many dialects of SQL, the execute statement is used to invoke a stored procedure.

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

How do I make an HTTP request in Swift?

In Swift 4.1 and Xcode 9.4.1.

JSON POST approach example. To check internet connection add Reachability.h & .m files from https://developer.apple.com/library/archive/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2

func yourFunctionName {
    //Check internet connection
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    print(networkStatus)
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg//Message
        //Call alert from shared class
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)
    } else {
        //Call spinner from shared class
        SharedClass.sharedInstance.activityIndicator(view: self.view)//Play spinner

        let parameters = "Your parameters here"
        var request = URLRequest(url: URL(string: url)!)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"

        print("URL : \(request)")

        request.httpBody = parameters.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            //Stop spinner
            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner
            //Print error in alert
            SharedClass.sharedInstance.alert(view: self, title: "", message: "\(String(describing: error!.localizedDescription))")
            return
            }

            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            do {
                let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
                print(response!)
                //Your code here                    
            } catch let error as NSError {
                print(error)
            }
        }

        task.resume()

    }

}

If you have interest to use this function in SharedClass

//My shared class
import UIKit
class SharedClass: NSObject {

static let sharedInstance = SharedClass()

func postRequestFunction(apiName: String , parameters: String, onCompletion: @escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {

    var URL =  "your URL here/index.php/***?"

    URL = URL.replacingOccurrences(of: "***", with: apiName)

    var request = URLRequest(url: URL(string: URL)!)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    print("shared URL : \(request)")
    request.httpBody = parameters.data(using: .utf8)

    var returnRes:[String:Any] = [:]
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        if let error = error {
            onCompletion(false, error, nil)
        } else {
            guard let data = data else {
                onCompletion(false, error, nil)
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
                do {
                   returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
                    onCompletion(true, nil, returnRes)

                } catch let error as NSError {
                   onCompletion(false, error, nil)
                }
            } else {
                onCompletion(false, error, nil)
            }
        }
    }
    task.resume()
}


private override init() {

}

And finally call this function like this....

SharedClass.sharedInstance.postRequestFunction(apiName: "Your API name", parameters: parameters) { (success, error, result) in
    print(result!)
    if success {
        //Your code here
    } else {
        print(error?.localizedDescription ?? "")
    }
}

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Regular expression to match any character being repeated more than 10 times

The regex you need is /(.)\1{9,}/.

Test:

#!perl
use warnings;
use strict;
my $regex = qr/(.)\1{9,}/;
print "NO" if "abcdefghijklmno" =~ $regex;
print "YES" if "------------------------" =~ $regex;
print "YES" if "========================" =~ $regex;

Here the \1 is called a backreference. It references what is captured by the dot . between the brackets (.) and then the {9,} asks for nine or more of the same character. Thus this matches ten or more of any single character.

Although the above test script is in Perl, this is very standard regex syntax and should work in any language. In some variants you might need to use more backslashes, e.g. Emacs would make you write \(.\)\1\{9,\} here.

If a whole string should consist of 9 or more identical characters, add anchors around the pattern:

my $regex = qr/^(.)\1{9,}$/;

Find length of 2D array Python

assuming input[row][col]

rows = len(input)
cols = len(list(zip(*input)))

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

Get paragraph text inside an element

Use jQuery:

$("li").find("p").html()

should work.

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

What are some good SSH Servers for windows?

VanDyke VShell is the best Windows SSH Server I've ever worked with. It is kind of expensive though ($250). If you want a free solution, freeSSHd works okay. The CYGWIN solution is always an option, I've found, however, that it is a lot of work & overhead just to get SSH.

What does `void 0` mean?

What does void 0 mean?

void[MDN] is a prefix keyword that takes one argument and always returns undefined.

Examples

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

What's the point of that?

It seems pretty useless, doesn't it? If it always returns undefined, what's wrong with just using undefined itself?

In a perfect world we would be able to safely just use undefined: it's much simpler and easier to understand than void 0. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.

The problem with using undefined was that undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined is a permissible variable name, so you could assign a new value to it at your own caprice.

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

void, on the other hand, cannot be overidden. void 0 will always return undefined. undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

Why void 0, specifically?

Why should we use void 0? What's so special about 0? Couldn't we just as easily use 1, or 42, or 1000000 or "Hello, world!"?

And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0 instead of some other argument is that 0 is short and idiomatic.

Why is this still relevant?

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

Changing SqlConnection timeout

If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.

Its usage is:

command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using delete, we could remove a reference from an object:

var obj = {};
obj.mypointer = null;
delete obj.mypointer;

2- The important point about the delete keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}] overriding the value of the array like array = [] would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;

As mentioned above, either setting storage.instance = null or delete storage.instance would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null then the storage object still has a property called instance (with the value null). If you delete storage.instance then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use instance.destroy in the destroy function you have no access to the actual instance pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

// Class constructor
var Class = function () {
     this.destroy = function (baseObject, refName) {
         delete baseObject[refName];
     };
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined

BUT if I were you I would simply stick to the first solution and delete the object like this:

storage.instance = null;
// OR
delete storage.instance;

WOW it was too much :)

Are SSL certificates bound to the servers ip address?

The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.

Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.

How to rename a class and its corresponding file in Eclipse?

Just rename the class in the source code. Eclipse will point out an error by underlining the class name with a red squiggly line. Hover on that line with your mouse pointer and eclipse will give you the option to rename compilation unit. Click on that.

How to generate a git patch for a specific commit?

Try:

git format-patch -1 <sha>

or

git format-patch -1 HEAD

According to the documentation link above, the -1 flag tells git how many commits should be included in the patch;

-<n>

     Prepare patches from the topmost commits.


Apply the patch with the command:

git am < file.patch

MVC Calling a view from a different controller

I'm not really sure if I got your question right. Maybe something like

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment's article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}

How to get the size of a file in MB (Megabytes)?

Example :

public static String getStringSizeLengthFile(long size) {

    DecimalFormat df = new DecimalFormat("0.00");

    float sizeKb = 1024.0f;
    float sizeMb = sizeKb * sizeKb;
    float sizeGb = sizeMb * sizeKb;
    float sizeTerra = sizeGb * sizeKb;


    if(size < sizeMb)
        return df.format(size / sizeKb)+ " Kb";
    else if(size < sizeGb)
        return df.format(size / sizeMb) + " Mb";
    else if(size < sizeTerra)
        return df.format(size / sizeGb) + " Gb";

    return "";
}

Changing background color of text box input not working when empty

You could have the CSS first style the textbox, then have js change it:

<input type="text" style="background-color: yellow;" id="subEmail" />

js:

function changeColor() {
  document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}

asp.net: How can I remove an item from a dropdownlist?

I have Done Like this, i have remove all items except the value coming as 1 and 3.

ListItemCollection liCol = ddlcustomertype.Items;
for (int i = 0; i < liCol.Count;i++ )
{
    ListItem li = liCol[i];
    if (li.Value != "1" || li.Value != "3")
        ddlcustomertype.Items.Remove(li);
}

What does status=canceled for a resource mean in Chrome Developer Tools?

In my case the cause of the problem was yet another one.

My application is sitting behind a proxy, and Chrome requests were being sent with the If-Modified-Since HTTP header. When this header is present the exepcted behavior is:

the server will send back the requested resource, with a 200 status, only if it has been last modified after the given date. If the request has not been modified since, the response will be a 304 without any body;

The Proxy was failing to meet this expectation, responding with a 304 status code but a non-empty body, thus causing the request to be cancelled.

After fixing the proxy behavior requests worked like a charm.

How do I capture SIGINT in Python?

If you want to ensure that your cleanup process finishes I would add on to Matt J's answer by using a SIG_IGN so that further SIGINT are ignored which will prevent your cleanup from being interrupted.

import signal
import sys

def signal_handler(signum, frame):
    signal.signal(signum, signal.SIG_IGN) # ignore additional signals
    cleanup() # give your process a chance to clean up
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
do_stuff()

Test if a string contains any of the strings from an array

A more groovyesque approach would be to use inject in combination with metaClass:

I would to love to say:

String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true

And the method would be:

myInput.metaClass.containsAny={List<String> notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}

If you need containsAny to be present for any future String variable then add the method to the class instead of the object:

String.metaClass.containsAny={notAllowedTerms->
   notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

JFrame.dispose() vs System.exit()

JFrame.dispose()

public void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

System.exit()

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

Simple way to count character occurrences in a string

You can look at sorting the string -- treat it as a char array -- and then do a modified binary search which counts occurrences? But I agree with @tofutim that traversing it is the most efficient -- O(N) versus O(N * logN) + O(logN)

How to get rid of underline for Link component of React Router?

There's also another way to properly remove the styling of the link. You have to give it style of textDecoration='inherit' and color='inherit' you can either add those as styling to the link tag like:

<Link style={{ color: 'inherit', textDecoration: 'inherit'}}>

or to make it more general just create a css class like:

.text-link {
    color: inherit;
    text-decoration: inherit;
}

And then just <Link className='text-link'>

How do I use DateTime.TryParse with a Nullable<DateTime>?

You can't because Nullable<DateTime> is a different type to DateTime. You need to write your own function to do it,

public bool TryParse(string text, out Nullable<DateTime> nDate)
{
    DateTime date;
    bool isParsed = DateTime.TryParse(text, out date);
    if (isParsed)
        nDate = new Nullable<DateTime>(date);
    else
        nDate = new Nullable<DateTime>();
    return isParsed;
}

Hope this helps :)

EDIT: Removed the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the "this" parameter will not work with Value Types.

P.S. The Bad Hoor in question is an old friend :)

How to store Java Date to Mysql datetime with JPA

java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());    
preparedStatement.setObject(param);

What is dtype('O'), in pandas?

It means:

'O'     (Python) objects

Source.

The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are to an existing type, or an error will be raised. The supported kinds are:

'b'       boolean
'i'       (signed) integer
'u'       unsigned integer
'f'       floating-point
'c'       complex-floating point
'O'       (Python) objects
'S', 'a'  (byte-)string
'U'       Unicode
'V'       raw data (void)

Another answer helps if need check types.

How do I debug Node.js applications?

I personally use JetBrains WebStorm as it's the only JavaScript IDE that I've found which is great for both frontend and backend JavaScript.

It works on multiple OS's and has Node.js debugging built-in (as well as a ton of other stuff](http://www.jetbrains.com/webstorm/features/index.html).

My only 'issues'/wishlist items are were:

  1. It seems to be more resource hungry on Mac than Windows It no longer seems an issue in version 6.
  2. It would be nice if it had Snippet support (like those of Sublime Text 2 - i.e. type 'fun' and tap 'tab' to put in a function. See @WickyNilliams comment below - With Live Templates you also have snippet support.

How do I create a readable diff of two spreadsheets using git diff?

Use Altova DiffDog

Use diffdog's XML diff mode and Grid View to review the differences in an easy to read tabular format. Text diff'ing is MUCH HARDER for spreadsheets of any complexity. With this tool, at least two methods are viable under various circumstances.

  1. Save As .xml

    To detect the differences of a simple, one sheet spreadsheet, save the Excel spreadsheets to compare as XML Spreadsheet 2003 with a .xml extension.

  2. Save As .xlsx

    To detect the differences of most spreadsheets in a modularized document model, save the Excel spreadsheets to compare as an Excel Workbook in .xlsx form. Open the files to diff with diffdog. It informs you that the file is a ZIP archive, and asks if you want to open it for directory comparison. Upon agreeing to directory comparison, it becomes a relatively simple matter of double-clicking logical parts of the document to diff them (with the XML diff mode). Most parts of the .xslx document are XML-formatted data. The Grid View is extremely useful. It is trivial to diff individual sheets to focus the analysis on areas that are known to have changed.

Excel's propensity to tweak certain attribute names with every save is annoying, but diffdog's XML diff'ing capabilities include the ability to filter certain kinds of differences. For example, Excel spreadsheets in XML form contain row and c elements that have s attributes (style) that rename with every save. Setting up a filter like c:s makes it much easier to view only content changes.

diffdog has a lot of diff'ing capability. I've listed the XML diff modes only simply because I haven't used another tool that I liked better when it comes to differencing Excel documents.

Convert String array to ArrayList

String[] words= new String[]{"ace","boom","crew","dog","eon"};
List<String> wordList = Arrays.asList(words);

open existing java project in eclipse

  1. File -> Import -> Existing Project into Workspace
  2. Browse for that directory.

Alternative: Check out the code in SVN to some folder

  1. Create a new folder in windows
  2. In eclipse File -> switchWorkspace -> newFolderName
  3. close the welcome window in eclipse
  4. In eclipse File -> Import -> Existing project into workspce-> select root dir -> browse and show the svn checkout folder

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

Spring Boot without the web server

For Spring boot v2.1.3.RELEASE, just add the follow properties into application.propertes:

spring.main.web-application-type=none

Scroll Element into View with Selenium

You can use this code snippet to scroll:

C#

var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();

There you have it

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

I encountered just the same problem when I wanted to store the dates in the DB as UTC and avoid using varchar and explicit String <-> java.util.Date conversions, or setting my whole Java app in the UTC time zone (because this could lead to another unexpected issues, if the JVM is shared across many applications).

So, there is an open source project DbAssist, which allows you to easily fix the read/write as UTC date from the database. Since you are using JPA Annotations to map the fields in the entity, all you have to do is to include the following dependency to your Maven pom file:

<dependency>
    <groupId>com.montrosesoftware</groupId>
    <artifactId>DbAssist-5.2.2</artifactId>
    <version>1.0-RELEASE</version>
</dependency>

Then you apply the fix (for Hibernate + Spring Boot example) by adding @EnableAutoConfiguration annotation before the Spring application class. For other setups installation instructions and more use examples, just refer to the project's github.

The good thing is that you don't have to modify the entities at all; you can leave their java.util.Date fields as they are.

5.2.2 has to correspond to the Hibernate version you are using. I am not sure, which version you are using in your project, but the full list of provided fixes is available on the wiki page of the project's github. The reason why the fix is different for various Hibernate versions is because Hibernate creators changed the API a couple of times between the releases.

Internally, the fix uses hints from divestoclimb, Shane and a few other sources in order to create a custom UtcDateType. Then it maps the standard java.util.Date with the custom UtcDateType which handles all the necessary time zone handling. The mapping of the types is achieved using @Typedef annotation in the provided package-info.java file.

@TypeDef(name = "UtcDateType", defaultForType = Date.class, typeClass = UtcDateType.class),
package com.montrosesoftware.dbassist.types;

You can find an article here which explains why such a time shift occurs at all and what are the approaches to solve it.

What is object slicing?

I just ran across the slicing problem and promptly landed here. So let me add my two cents to this.

Let's have an example from "production code" (or something that comes kind of close):


Let's say we have something that dispatches actions. A control center UI for example.
This UI needs to get a list of things that are currently able to be dispatched. So we define a class that contains the dispatch-information. Let's call it Action. So an Action has some member variables. For simplicity we just have 2, being a std::string name and a std::function<void()> f. Then it has an void activate() which just executes the f member.

So the UI gets a std::vector<Action> supplied. Imagine some functions like:

void push_back(Action toAdd);

Now we have established how it looks from the UI's perspective. No problem so far. But some other guy who works on this project suddenly decides that there are specialized actions that need more information in the Action object. For what reason ever. That could also be solved with lambda captures. This example is not taken 1-1 from the code.

So the guy derives from Action to add his own flavour.
He passes an instance of his home-brewed class to the push_back but then the program goes haywire.

So what happened?
As you might have guessed: the object has been sliced.

The extra information from the instance has been lost, and f is now prone to undefined behaviour.


I hope this example brings light about for those people who can't really imagine things when talking about As and Bs being derived in some manner.

What is the difference between Amazon SNS and Amazon SQS?

In simple terms,

  • SNS - sends messages to the subscriber using push mechanism and no need of pull.

  • SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.

A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.

Reference from Amazon SNS FAQs.

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Your class needs to extend from ActionBarActivity, rather than a plain Activity in order to use the getSupport*() methods.

Update [2015/04/23]: With the release of Android Support Library 22.1, you should now extend AppCompatActivity. Also, you no longer have to extend ActionBarActivity or AppCompatActivity, as you can now incorporate an AppCompatDelegate instance in any activity.

Plotting categorical data with pandas and matplotlib

You can simply use value_counts with sort option set to False. This will preserve ordering of the categories

df['colour'].value_counts(sort=False).plot.bar(rot=0)

link to image

jQuery & CSS - Remove/Add display:none

jQuery's .show() and .hide() functions are probably your best bet.

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I encountered the same problem with Android devices but not iOS devices. Managed to resolve by specifying position:relative in the outer div of the absolutely positioned elements (with overflow:hidden for outer div)

python setup.py uninstall

Extending on what Martin said, recording the install output and a little bash scripting does the trick quite nicely. Here's what I do...

for i in $(less install.record);
sudo rm $i;
done;

And presto. Uninstalled.

Netbeans - Error: Could not find or load main class

This condition happens to me every 6-months or so. I think it happens when closing NetBeans under very low memory conditions. I discovered that it could be easily corrected by (1) Rename your project, including its folder name using right-click on project explorer's project name---I put a simple suffix on the original name ("_damaged"). (2) Try BUILD. If that is successful, which it is for me, give three cheers. (3) Repeat step (1) to restore the original project name. BUILD and RUN should start without trouble. I guess that the 'rename the project and folder' process causes a special rediscovery of the applications main location.

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

Converting year and month ("yyyy-mm" format) to a date?

I think @ben-rollert's solution is a good solution.

You just have to be careful if you want to use this solution in a function inside a new package.

When developping packages, it's recommended to use the syntaxe packagename::function_name() (see http://kbroman.org/pkg_primer/pages/depends.html).

In this case, you have to use the version of as.Date() defined by the zoo library.

Here is an example :

> devtools::session_info()
Session info ----------------------------------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.3.1 (2016-06-21)
 system   x86_64, linux-gnu           
 ui       RStudio (1.0.35)            
 language (EN)                        
 collate  C                           
 tz       <NA>                        
 date     2016-11-09                  

Packages --------------------------------------------------------------------------------------------------------------------------------------------------------

 package  * version date       source        
 devtools   1.12.0  2016-06-24 CRAN (R 3.3.1)
 digest     0.6.10  2016-08-02 CRAN (R 3.2.3)
 memoise    1.0.0   2016-01-29 CRAN (R 3.2.3)
 withr      1.0.2   2016-06-20 CRAN (R 3.2.3)

> as.Date(zoo::as.yearmon("1989-10", "%Y-%m")) 
Error in as.Date.default(zoo::as.yearmon("1989-10", "%Y-%m")) : 
  do not know how to convert 'zoo::as.yearmon("1989-10", "%Y-%m")' to class “Date”

> zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))
[1] "1989-10-01"

So if you're developping a package, the good practice is to use :

zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))

What exactly is a Maven Snapshot and why do we need it?

Maven versions can contain a string literal "SNAPSHOT" to signify that a project is currently under active development.

For example, if your project has a version of “1.0-SNAPSHOT” and you deploy this project’s artifacts to a Maven repository, Maven would expand this version to “1.0-20080207-230803-1” if you were to deploy a release at 11:08 PM on February 7th, 2008 UTC. In other words, when you deploy a snapshot, you are not making a release of a software component; you are releasing a snapshot of a component at a specific time.

So mainly snapshot versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a snapshot release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build. Similarly, if the next release of your system is going to have a version “1.8,” your project would have a “1.8-SNAPSHOT” version until it was formally released.

For example , the following dependency would always download the latest 1.8 development JAR of spring:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring</artifactId>
        <version>1.8-SNAPSHOT”</version>
    </dependency>

Maven

An example of maven release process

enter image description here

Getting Class type from String

You can use the forName method of Class:

Class cls = Class.forName(clsName);
Object obj = cls.newInstance();

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Are you sure you are not using a wrong path in the url field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.

Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.

Instant run in Android Studio 2.0 (how to turn off)

Using Android Studio newest version and update Android Plugin to 'newest alpha version`, I can disable Instant Run: Android studio Instant Run view with Version highlighted Android studio Project view with Android Plugin Version highlighted

Try to update Android Studio.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

In Eclipse goto Run->Run Configuration find the Name of the class you have been running, select it, click the Target tab then in "Additional Emulator Command Line Options" add:

-Xms512M -Xmx1524M

then click apply.

Two arrays in foreach loop

You can use array_merge to combine two arrays and then iterate over them.

$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);

MSVCP120d.dll missing

I have the same problem with you when I implement OpenCV 2.4.11 on VS 2015. I tried to solve this problem by three methods one by one but they didn't work:

  1. download MSVCP120.DLL online and add it to windows path and OpenCV bin file path
  2. install Visual C++ Redistributable Packages for Visual Studio 2013 both x86 and x86
  3. adjust Debug mode. Go to configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd)

Finally I solved this problem by reinstalling VS2015 with selecting all the options that can be installed, it takes a lot space but it really works.

How to drop a list of rows from Pandas dataframe?

If the DataFrame is huge, and the number of rows to drop is large as well, then simple drop by index df.drop(df.index[]) takes too much time.

In my case, I have a multi-indexed DataFrame of floats with 100M rows x 3 cols, and I need to remove 10k rows from it. The fastest method I found is, quite counterintuitively, to take the remaining rows.

Let indexes_to_drop be an array of positional indexes to drop ([1, 2, 4] in the question).

indexes_to_keep = set(range(df.shape[0])) - set(indexes_to_drop)
df_sliced = df.take(list(indexes_to_keep))

In my case this took 20.5s, while the simple df.drop took 5min 27s and consumed a lot of memory. The resulting DataFrame is the same.

Using Node.JS, how do I read a JSON file into (server) memory?

The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

You can then easily load this in your node.js application using require

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);

HTML span align center not working?

Just use word-wrap:break-word; in the css. It works.

Setting default values to null fields when mapping with Jackson

Make the member private and add a setter/getter pair. In your setter, if null, then set default value instead. Additionally, I have shown the snippet with the getter also returning a default when internal value is null.

class JavaObject {
    private static final String DEFAULT="Default Value";

    public JavaObject() {
    }

    @NotNull
    private String notNullMember;
    public void setNotNullMember(String value){
            if (value==null) { notNullMember=DEFAULT; return; }
            notNullMember=value;
            return;
    }

    public String getNotNullMember(){
            if (notNullMember==null) { return DEFAULT;}
            return notNullMember;
    }

    public String optionalMember;
}

How to set a Header field on POST a form?

Set a cookie value on the page, and then read it back server side.

You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.

What is the best comment in source code you have ever encountered?

From a google code project:

# This job would be great if it wasn't for the fucking customers.

Android check internet connection

This method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}

in manifest,

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

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com"); 
        //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
    }
}

List of all special characters that need to be escaped in a regex

Assuming that you have and trust (to be authoritative) the list of escape characters Java regex uses (would be nice if these characters were exposed in some Pattern class member) you can use the following method to escape the character if it is indeed necessary:

private static final char[] escapeChars = { '<', '(', '[', '{', '\\', '^', '-', '=', '$', '!', '|', ']', '}', ')', '?', '*', '+', '.', '>' };

private static String regexEscape(char character) {
    for (char escapeChar : escapeChars) {
        if (character == escapeChar) {
            return "\\" + character;
        }
    }
    return String.valueOf(character);
}

How to create a HTTP server in Android?

You can try Restlet edition for android:

The source can be downloaded from Restlet website:

How to test if a double is zero?

Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

If this has anything to do with money, do not use float or double, instead use BigDecimal.

View markdown files offline

I just installed https://github.com/ypocat/gfms. It does a very good job rendering github flavored markdown. It detects changes in your markdown, so you just put your browser and editor side-by-side. It is Node.js, so it should work fine on any platform.

If you have Node.js is installed, the installation is simple:

  1. sudo npm install -g gfms
  2. gfms --port 9999 (in your project directory)
  3. http://localhost:9999/ (open with any browser)

Count how many rows have the same value

SELECT 
   COUNT(NUM) as 'result' 
FROM 
   Table1 
GROUP BY 
   NUM 
HAVING NUM = 1

How to start anonymous thread class

Since anonymous classes extend the given class you can store them in a variable.

eg.

Thread t = new Thread()
{
    public void run() {
        System.out.println("blah");
    }
};
t.start();

Alternatively, you can just call the start method on the object you have immediately created.

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();
// similar to new Thread().start();

Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).

eg

new Thread(new Runnable()
{
    @Override
    public void run() {
        System.out.println("blah");
    }
}).start();

Difference between ProcessBuilder and Runtime.exec()

Yes there is a difference.

  • The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments.

  • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)

So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.

MySQL - How to select data by string length

Having a look at MySQL documentation for the string functions, we can also use CHAR_LENGTH() and CHARACTER_LENGTH() as well.

How can I create download link in HTML?

You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly

_x000D_
_x000D_
<div className="col-6">_x000D_
                    <a  download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
                </div>
_x000D_
_x000D_
_x000D_

another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.

_x000D_
_x000D_
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
  <img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
_x000D_
_x000D_

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

How can I create Min stl priority_queue?

You can do it in multiple ways:
1. Using greater as comparison function :

 #include <bits/stdc++.h>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> >pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<< " ";
    }
    return 0;
}

2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :

int main()
{
    priority_queue<int>pq2;
    pq2.push(-1); //for +1
    pq2.push(-2); //for +2
    pq2.push(-3); //for +3
    pq2.push(4);  //for -4

    while(!pq2.empty())
    {
        int r = pq2.top();
        pq2.pop();
        cout<<-r<<" ";
    }

    return 0;
}

3. Using custom structure or class :

struct compare
{
    bool operator()(const int & a, const int & b)
    {
        return a>b;
    }
};

int main()
{

    priority_queue<int,vector<int>,compare> pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<<" ";
    }

    return 0;
}

4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

    struct people
    {
        int age,salary;

    };
    struct compare{
    bool operator()(const people & a, const people & b)
        {
            if(a.salary==b.salary)
            {
                return a.age>b.age;
            }
            else
            {
                return a.salary>b.salary;
            }

    }
    };
    int main()
    {

        priority_queue<people,vector<people>,compare> pq;
        people person1,person2,person3;
        person1.salary=100;
        person1.age = 50;
        person2.salary=80;
        person2.age = 40;
        person3.salary = 100;
        person3.age=40;


        pq.push(person1);
        pq.push(person2);
        pq.push(person3);

        while(!pq.empty())
        {
            people r = pq.top();
            pq.pop();
            cout<<r.salary<<" "<<r.age<<endl;
    }
  1. Same result can be obtained by operator overloading :

    struct people
    {
    int age,salary;
    
    bool operator< (const people & p)const
    {
        if(salary==p.salary)
        {
            return age>p.age;
        }
        else
        {
            return salary>p.salary;
        }
    }};
    

    In main function :

    priority_queue<people> pq;
    people person1,person2,person3;
    person1.salary=100;
    person1.age = 50;
    person2.salary=80;
    person2.age = 40;
    person3.salary = 100;
    person3.age=40;
    
    
    pq.push(person1);
    pq.push(person2);
    pq.push(person3);
    
    while(!pq.empty())
    {
        people r = pq.top();
        pq.pop();
        cout<<r.salary<<" "<<r.age<<endl;
    }
    

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

How do I get Bin Path?

This is what I used to accomplish to this:

System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

to_string is not a member of std, says g++ (mingw)

to_string() is only present in c++11 so if c++ version is less use some alternate methods such as sprintf or ostringstream

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile

How to stretch the background image to fill a div

You can add:

#div2{
    background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
    background-size: 100% 100%;
    height:180px;
    width:200px;
    border: 1px solid red;
}

You can read more about it here: css3 background-size

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

How to call a method in another class in Java?

Try this :

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}

How to get current SIM card number in Android?

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

=================================================================================

Its been almost 6 months and I believe I should update this with an alternative solution you might want to consider.

As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.

Permission:

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

Code:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

ArrayList<String> googleAccounts = new ArrayList<String>();
for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}

Check actype for whatsapp account

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Of course you may not get it if user did not install Whatsapp, but its worth to try anyway. And remember you should always ask user for confirmation.

How to embed PDF file with responsive width

I did that mistake once - embedding PDF files in HTML pages. I will suggest that you use a JavaScript library for displaying the content of the PDF. Like https://github.com/mozilla/pdf.js/

Double.TryParse or Convert.ToDouble - which is faster and safer?

The .NET Framework design guidelines recommend using the Try methods. Avoiding exceptions is usually a good idea.

Convert.ToDouble(object) will do ((IConvertible) object).ToDouble(null);

Which will call Convert.ToDouble(string, null)

So it's faster to call the string version.

However, the string version just does this:

if (value == null)
{
    return 0.0;
}
return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);

So it's faster to do the double.Parse directly.

Javascript set img src

Wow! when you use src then src of searchPic must be used also.

document["pic1"].src = searchPic.src

looks better

Can I obtain method parameter name using Java reflection?

You can retrieve the method with reflection and detect its argument types. Check getParameterTypes().

However, you can't tell the name of the argument used.

How do I search for files in Visual Studio Code?

If using vscodevim extension, ctrl + p won't work so I saw another answer using:

ctrl + shift + p

which opens the command palette. Hit backspace to remove the '>' and then start typing your filename.

Disable Chrome strict MIME type checking

In my case, I turned off X-Content-Type-Options on nginx then works fine. But make sure this declines your security level a little. Would be a temporally fix.

# Not work
add_header X-Content-Type-Options nosniff;
# OK (comment out)
#add_header X-Content-Type-Options nosniff;

It'll be the same for apache.

<IfModule mod_headers.c>
  #Header set X-Content-Type-Options nosniff
</IfModule>

StringStream in C#

You can use tandem of MemoryStream and StreamReader classes:

void Main()
{
    string myString;

    using (var stream = new MemoryStream())
    {
        Print(stream);

        stream.Position = 0;
        using (var reader = new StreamReader(stream))
        {
            myString = reader.ReadToEnd();
        }
    }
}

How to make GREP select only numeric values?

function getPercentUsed() {
    $sys = system("df -h /dev/sda6 --output=pcent | grep -o '[0-9]*'", $val);
    return $val[0];
}

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

<embed> vs. <object>

Answer updated for 2020:

Both <object> and <embed> are included in the WHAT-WG HTML Living Standard (Sept 2020).


<object>

The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.


<embed>

The embed element provides an integration point for an external (typically non-HTML) application or interactive content.


Are there advantages/disadvantages to using one tag vs. the other?

The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object> over <embed> but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.

[...] you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.

Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.

Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies#The_%3Cembed%3E_and_%3Cobject%3E_elements

Setting focus on an HTML input box on page load

You could also use:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

And then in your JavaScript:

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}

How do I change data-type of pandas data frame to string with a defined format?

If you could reload this, you might be able to use dtypes argument.

pd.read_csv(..., dtype={'COL_NAME':'str'})

How to configure log4j.properties for SpringJUnit4ClassRunner?

The new tests you wrote (directly or indirectly) use classes that log using Log4j.

Log4J needs to be configured for this logging to work properly.

Put a log4j.properties (or log4j.xml) file in the root of your test classpath.

It should have some basic configuration such as

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

An appender outputs to the console by default, but you can also explicitly set the target like this:

log4j.appender.A1.Target=System.out

This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,

Log4J Logging will then be properly configured and this warning will disappear.

Streaming via RTSP or RTP in HTML5

Chrome not implement support RTSP streaming. An important project to check it WebRTC.

"WebRTC is a free, open project that provides browsers and mobile applications with Real-Time Communications (RTC) capabilities via simple APIs"

Supported Browsers:

Chrome, Firefox and Opera.

Supported Mobile Platforms:

Android and IOS

http://www.webrtc.org/

Spring Security with roles and permissions

I'm the author of the article in question.

No doubt there are multiple ways to do it, but the way I typically do it is to implement a custom UserDetails that knows about roles and permissions. Role and Permission are just custom classes that you write. (Nothing fancy--Role has a name and a set of Permission instances, and Permission has a name.) Then the getAuthorities() returns GrantedAuthority objects that look like this:

PERM_CREATE_POST, PERM_UPDATE_POST, PERM_READ_POST

instead of returning things like

ROLE_USER, ROLE_MODERATOR

The roles are still available if your UserDetails implementation has a getRoles() method. (I recommend having one.)

Ideally you assign roles to the user and the associated permissions are filled in automatically. This would involve having a custom UserDetailsService that knows how to perform that mapping, and all it has to do is source the mapping from the database. (See the article for the schema.)

Then you can define your authorization rules in terms of permissions instead of roles.

Hope that helps.

How can I reverse a list in Python?

The most direct translation of your requirement into Python is this for statement:

for i in xrange(len(array) - 1, -1, -1):
   print i, array[i]

This is rather cryptic but may be useful.

SSL "Peer Not Authenticated" error with HttpClient 4.1

This is thrown when

... the peer was not able to identify itself (for example; no certificate, the particular cipher suite being used does not support authentication, or no peer authentication was established during SSL handshaking) this exception is thrown.

Probably the cause of this exception (where is the stacktrace) will show you why this exception is thrown. Most likely the default keystore shipped with Java does not contain (and trust) the root certificate of the TTP that is being used.

The answer is to retrieve the root certificate (e.g. from your browsers SSL connection), import it into the cacerts file and trust it using keytool which is shipped by the Java JDK. Otherwise you will have to assign another trust store programmatically.

batch script - read line by line

For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.

set SOURCE=path\with spaces\to\my.log
FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
    ECHO %%A
)

To explain:

(path\with spaces\to\my.log)

Will not parse, because spaces. If it becomes:

("path\with spaces\to\my.log")

It will be handled as a string rather than a file path.

"usebackq delims=" 

See docs will allow the path to be used as a path (thanks to Stephan).

How to detect running app using ADB command

You can use

adb shell ps | grep apps | awk '{print $9}'

to produce an output like:

com.google.process.gapps
com.google.android.apps.uploader
com.google.android.apps.plus
com.google.android.apps.maps
com.google.android.apps.maps:GoogleLocationService
com.google.android.apps.maps:FriendService
com.google.android.apps.maps:LocationFriendService

adb shell ps returns a list of all running processes on the android device, grep apps searches for any row with contains "apps", as you can see above they are all com.google.android.APPS. or GAPPS, awk extracts the 9th column which in this case is the package name.

To search for a particular package use

adb shell ps | grep PACKAGE.NAME.HERE | awk '{print $9}'

i.e adb shell ps | grep com.we7.player | awk '{print $9}'

If it is running the name will appear, if not there will be no result returned.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I liked galloglas's code, and I changed the main function so that it shows a sorted list of total size by application:

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    sizes = {}
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)
        if (fileinfo['mode'] & 0xE000) == 0x8000:
        sizes[fileinfo['domain']]= sizes.get(fileinfo['domain'],0) + fileinfo['filelen']
    for domain in sorted(sizes, key=sizes.get):
        print "%-60s %11d (%dMB)" % (domain, sizes[domain], int(sizes[domain]/1024/1024))

That way you can figure out what application is eating all that space.

How to detect scroll direction

Here is a sample showing an easy way to do it. The script is:

$(function() {
  var _t = $("#container").scrollTop();
  $("#container").scroll(function() {
    var _n = $("#container").scrollTop();
    if (_n > _t) {
      $("#target").text("Down");
    } else {
      $("#target").text("Up");
    }
    _t = _n;
  });
});

The #container is your div id. The #target is just to see it working. Change to what you want when up or when down.

EDIT

The OP didn't say before, but since he's using a div with overflow: hidden, scrolling doesn't occur, then the script to detect the scroll is the least of it. Well, how to detect something that does not happen?!

So, the OP himself posted the link with what he wants, so why not use that library? http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js.

The call is just:

$(function() {
    $(".scrollable").scrollable({ vertical: true, mousewheel: true });
});

Curl GET request with json parameter

If you want to send your data inside the body, then you have to make a POST or PUT instead of GET.

For me, it looks like you're trying to send the query with uri parameters, which is not related to GET, you can also put these parameters on POST, PUT and so on.

The query is an optional part, separated by a question mark ("?"), that contains additional identification information that is not hierarchical in nature. The query string syntax is not generically defined, but it is commonly organized as a sequence of = pairs, with the pairs separated by a semicolon or an ampersand.

For example:

curl http://server:5050/a/c/getName?param0=foo&param1=bar

How to install the current version of Go in Ubuntu Precise

  1. Download say, go1.6beta1.linux-amd64.tar.gz from https://golang.org/dl/ into /tmp

wget https://storage.googleapis.com/golang/go1.6beta1.linux-amd64.tar.gz -o /tmp/go1.6beta1.linux-amd64.tar.gz

  1. un-tar into /usr/local/bin

sudo tar -zxvf go1.6beta1.linux-amd64.tar.gz -C /usr/local/bin/

  1. Set GOROOT, GOPATH, [on ubuntu add following to ~/.bashrc]

mkdir ~/go export GOPATH=~/go export PATH=$PATH:$GOPATH/bin export GOROOT=/usr/local/bin/go export PATH=$PATH:$GOROOT/bin

  1. Verify

go version should show be

go version go1.6beta1 linux/amd64

go env should show be

GOARCH="amd64" GOBIN="" GOEXE="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOOS="linux" GOPATH="/home/vats/go" GORACE="" GOROOT="/usr/local/bin/go" GOTOOLDIR="/usr/local/bin/go/pkg/tool/linux_amd64" GO15VENDOREXPERIMENT="1" CC="gcc" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0" CXX="g++" CGO_ENABLED="1"

How to center an unordered list?

http://jsfiddle.net/psbu2/3/

If it is possible for you to use your own list bullets

Try this:

<html>
    <head>
        <style type="text/css">

            ul {
                margin:0;
                padding:0;
                text-align: center;
                list-style:none;                
            }
            ul  li {
                padding: 2px 5px;               
            }

            ul li:before {
                content:url(http://www.un.org/en/oaj/unjs/efiling/added/images/bullet-list-icon-blue.jpg);;
            }
        </style>
    </head>
    <body>

            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
            </ul>

    </body>
</html>

finding first day of the month in python

Use dateutil.

from datetime import date
from dateutil.relativedelta import relativedelta

today = date.today()
first_day = today.replace(day=1)
if today.day > 25:
    print(first_day + relativedelta(months=1))
else:
    print(first_day)

How to find the size of a table in SQL?

You may refer the answer by Marc_s in another thread, Very useful.

Get size of all tables in database

getting "No column was specified for column 2 of 'd'" in sql server cte?

I had a similar query and a similar issue.

SELECT
    *
FROM
    Users ru
    LEFT OUTER JOIN 
    (
        SELECT ru1.UserID, COUNT(*)
        FROM Referral r
        LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
        GROUP BY ru1.UserID
    ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

I found that SQL Server was choking on the COUNT(*) column, and was giving me the error No column was specified for column 2.

Putting an alias on the COUNT(*) column fixed the issue.

  SELECT
        *
    FROM
        Users ru
        LEFT OUTER JOIN 
        (
            SELECT ru1.UserID, COUNT(*) AS -->MyCount<--
            FROM Referral r
            LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
            GROUP BY ru1.UserID
        ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

PHP check if date between two dates

You are comparing the dates as strings, which won't work because the comparison is lexicographical. It's the same issue as when sorting a text file, where a line 20 would appear after a line 100 because the contents are not treated as numbers but as sequences of ASCII codes. In addition, the dates created are all wrong because you are using a string format string where a timestamp is expected (second argument).

Instead of this you should be comparing timestamps of DateTime objects, for instance:

 $paymentDate = date_create();
 $contractDateBegin = date_create_from_format('d/m/Y', '01/01/2001');
 $contractDateEnd = date_create_from_format('d/m/Y', '01/01/2015');

Your existing conditions will then work correctly.

What's the purpose of SQL keyword "AS"?

Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.

Example 1

SELECT P.ProductName,
       P.ProductGroup,
       P.ProductRetailPrice
FROM   Products AS P

Example 2

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.

Example 4

SELECT P.ProductName AS "Product",
       P.ProductRetailPrice AS "Retail Price",
       O.Quantity AS "Quantity Ordered"
FROM   Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE  O.OrderID = 123456

Output of Example 4

Product             Retail Price     Quantity Ordered
Blue Raspberry Gum  $10 pk/$50 Case  2 Cases
Twizzler            $5 pk/$25 Case   10 Cases

About the Full Screen And No Titlebar from manifest

Try using these theme: Theme.AppCompat.Light.NoActionBar

Mi Style XML file looks like these and works just fine:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

Convert a String to a byte array and then back to the original String

import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
{
    String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

    while(true)
    {
        len = is.read(buf);
        if(len < 0) break;
        md.update(buf, 0, len);
    }

    // close the input stream

    is.close();

    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
    {
        System.out.println(b + ", ");
    }

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);

    System.out.println();

    System.out.println("===")

    System.out.println(verification);

    System.out.println("Equals? " + verification.equals(compare));

}

}

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

How to tackle daylight savings using TimeZone in Java

Instead of entering "EST" for the timezone you can enter "EST5EDT" as such. As you noted, just "EDT" does not work. This will account for the daylight savings time issue. The code line looks like this:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST5EDT"));

T-test in Pandas

EDIT: I had not realized this was about the data format. You could use

import pandas as pd
import scipy
two_data = pd.DataFrame(data, index=data['Category'])

Then accessing the categories is as simple as

scipy.stats.ttest_ind(two_data.loc['cat'], two_data.loc['cat2'], equal_var=False)

The loc operator accesses rows by label.


As @G Garcia said

one sided or two sided dependent or independent

If you have two independent samples but you do not know that they have equal variance, you can use Welch's t-test. It is as simple as

scipy.stats.ttest_ind(cat1['values'], cat2['values'], equal_var=False)

For reasons to prefer Welch's test, see https://stats.stackexchange.com/questions/305/when-conducting-a-t-test-why-would-one-prefer-to-assume-or-test-for-equal-vari.

For two dependent samples, you can use

scipy.stats.ttest_rel(cat1['values'], cat2['values'])

Save matplotlib file to a directory

The simplest way to do this is as follows:


save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)

The image is going to be saved in the save_results_to directory with name image.png

SQL Error: ORA-00936: missing expression

You did two mistakes . I think you misplace FROM and WHERE keywords.

SELECT DISTINCT Description, Date as treatmentDate
     FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL,  doothey.Item.I --Here you use "." operator to "I" alias 
  WHERE  -- WHERE should be located here. 
   P.PatientID = A.PatientID
    AND A.AccountNo = AL.AccountNo
    AND AL.ItemNo = I.ItemNo
    AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

Javascript - validation, numbers only

var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
   elem[i].addEventListener('keypress', function(event){
      var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
      var validIndex = keys.indexOf(event.charCode);
      if(validIndex == -1){
         event.preventDefault();
      }
  });
}

Are there best practices for (Java) package organization?

Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:

  • Follow java package naming conventions
  • Structure your packages according to their functional role as well as their business role
    • Break down your packages according to their functionality or modules. e.g. com.company.product.modulea
    • Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g. com.company.product.module.web or com.company.product.module.util etc.
    • Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.
  • If your project is small, keep it simple with few packages. e.g. com.company.product.model and com.company.product.util, etc.
  • Take a look at some of the popular open source projects out there on Apache projects. See how they use structuring, for various sized projects.
  • Also consider build and distribution when naming ( allowing you to distribute your api or SDK in a different package, see servlet api)

After a few experiments and trials you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.

How to increase application heap size in Eclipse?

Open eclipse.ini

Search for -Xmx512m or maybe more size it is.

Just change it to a required size such as I changed it to -Xmx1024m

Changing .gitconfig location on Windows

Solution without having to change Windows HOME variable
OS: Windows 10
git version: 2.27.0.windows.1

I use portable version of Git, so all my config files are on my pen-drive(E:). This is what worked for me:

  1. Download portable Git from https://git-scm.com/. Run the file and install it in the required location. I installed it in E:\git.
  2. Run git-bash.exe from E:\git.
  3. I wanted to put .gitconfig and other bash files in E, so I created a folder called home where I want them all in.
    mkdir home
  4. Go to etc folder and open the file called profile (In my case, it's E:\git\etc\profile)
  5. Add absolute path to the home directory we created (or to the directory where you want to have your .gitconfig file located) at the end of the profile file.
    HOME="E:\git\home"

Now it no longer searches in the C:\Users<username> directory for .gitconfig but only looks in your set path above.

$ git config --global --list
fatal: unable to read config file 'E:/git/home/.gitconfig': No such file or directory

It gave an error because there isn't a .gitconfig file there yet. This is just to demonstrate that we have successfully changed the location of the .gitconfig file without changing the HOME directory in Windows.

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

You could use serialize

<input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">

But best way in this case use the json_encode method in your blade and json_decode in controller.

htaccess "order" Deny, Allow, Deny

Not answering OPs question directly, but for the people finding this question in search of clarity on what's the difference between allow,deny and deny,allow:

Read the comma as a "but".

  • allow but deny: whitelist with exceptions.
    everything is denied, except items on the allow list, except items on the deny list
  • deny but allow: blacklist with exceptions.
    everything is allowed, except items on the deny list, except items on the allow list

allow only one country access, but exclude proxies within this country

OP needed a whitelist with exceptions, therefore allow,deny instead of deny,allow

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

What is the dual table in Oracle?

The DUAL table is a special one-row table present by default in all Oracle database installations. It is suitable for use in selecting a pseudocolumn such as SYSDATE or USER

The table has a single VARCHAR2(1) column called DUMMY that has a value of "X"

You can read all about it in http://en.wikipedia.org/wiki/DUAL_table

Windows 7, 64 bit, DLL problems

I solved the problem. When I registered the OCX files, I ran it with the Command Window that had been executed as an administrator.

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

SQL, Postgres OIDs, What are they and why are they useful?

If you still use OID, it would be better to remove the dependency on it, because in recent versions of Postgres it is no longer supported. This can stop (temporarily until you solve it) your migration from version 10 to 12 for example.

See also: https://dev.to/rafaelbernard/postgresql-pgupgrade-from-10-to-12-566i

Changing one character in a string

Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings):

s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg

edit: Changed str to s

edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with unicode.

How to remove docker completely from ubuntu 14.04

Probably your problem is that for Docker that has been installed from default Ubuntu repository, the package name is docker.io

Or package name may be something like docker-ce. Try running

dpkg -l | grep -i docker

to identify what installed package you have

So you need to change package name in commands from https://stackoverflow.com/a/31313851/2340159 to match package name. For example, for docker.io it would be:

sudo apt-get purge -y docker.io
sudo apt-get autoremove -y --purge docker.io
sudo apt-get autoclean

It adds:

The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:

sudo rm -rf /var/lib/docker

Remove docker from apparmor.d:

sudo rm /etc/apparmor.d/docker

Remove docker group:

sudo groupdel docker

How to send post request with x-www-form-urlencoded body

As you set application/x-www-form-urlencoded as content type so data sent must be like this format.

String urlParameters  = "param1=data1&param2=data2&param3=data3";

Sending part now is quite straightforward.

byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
   wr.write( postData );
}

Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded.

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");    
        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }    
    return result.toString();
}

Associating existing Eclipse project with existing SVN repository

I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)

subclipse not showing "share project" option on project context menu in eclipse

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

How to add/update an attribute to an HTML element using JavaScript?

Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

$('#element').attr( 'title', 'foo' );

Load image from resources

You can do this using the ResourceManager:

public bool info(string channel)
{
   object o = Properties.Resources.ResourceManager.GetObject(channel);
   if (o is Image)
   {
       channelPic.Image = o as Image;
       return true;
   }
   return false;
}

IE8 css selector

There aren't any selector hacks for IE8. The best resource for this issue is http://browserhacks.com/#ie

If you want to target specific IE8 you should do comment in html

<!--[if IE 8]> Internet Explorer 8 <![endif]-->

or you could use attribute hacks like:

/* IE6, IE7, IE8, but also IE9 in some cases :( */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE8, IE9 */
#anotherone  {color: blue\0/;} /* must go at the END of all rules */

For more info on this one check: http://www.paulirish.com/2009/browser-specific-css-hacks/

A terminal command for a rooted Android to remount /System as read/write

I had the same problem. So here is the real answer: Mount the system under /proc. Here is my command:

mount -o rw,remount /proc /system

It works, and in fact is the only way I can overcome the Read-only System problem.

How to clear APC cache entries?

My work-around for Symfony build having loot of instances at the same server:

Step 1. Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

file_put_contents('clearAPCU','yes sir i can buggy')

Step 2. On index file at start add clearing code and remove marker file.

if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}

Step 2. Run app.

jQuery Set Selected Option Using Next

From version 1.6.1 on, it's advisable to use the method prop for boolean attributes/properties such as selected, readonly, enabled,...

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);

For more info, please refer to to http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

Failed to load resource under Chrome

Check the network tab to see if Chrome failed to download any resource file.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

You can use:

  1. size_t type, to remove warning messages
  2. iterators + distance (like are first hint)
  3. only iterators
  4. function object

For example:

// simple class who output his value
class ConsoleOutput
{
public:
  ConsoleOutput(int value):m_value(value) { }
  int Value() const { return m_value; }
private:
  int m_value;
};

// functional object
class Predicat
{
public:
  void operator()(ConsoleOutput const& item)
  {
    std::cout << item.Value() << std::endl;
  }
};

void main()
{
  // fill list
  std::vector<ConsoleOutput> list;
  list.push_back(ConsoleOutput(1));
  list.push_back(ConsoleOutput(8));

  // 1) using size_t
  for (size_t i = 0; i < list.size(); ++i)
  {
    std::cout << list.at(i).Value() << std::endl;
  }

  // 2) iterators + distance, for std::distance only non const iterators
  std::vector<ConsoleOutput>::iterator itDistance = list.begin(), endDistance = list.end();
  for ( ; itDistance != endDistance; ++itDistance)
  {
    // int or size_t
    int const position = static_cast<int>(std::distance(list.begin(), itDistance));
    std::cout << list.at(position).Value() << std::endl;
  }

  // 3) iterators
  std::vector<ConsoleOutput>::const_iterator it = list.begin(), end = list.end();
  for ( ; it != end; ++it)
  {
    std::cout << (*it).Value() << std::endl;
  }
  // 4) functional objects
  std::for_each(list.begin(), list.end(), Predicat());
}

Get list of all input objects using JavaScript, without accessing a form object

querySelectorAll returns a NodeList which has its own forEach method:

document.querySelectorAll('input').forEach( input => {
  // ...
});

getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

Array.from(document.getElementsByTagName('input')).forEach( input => {
  // ...
});

"Unable to launch the IIS Express Web server" error

In my case i tried following things to fix this problem.

  1. Delete the iisexpress folder from "MyDocuments"

  2. Go to Solution Explorer --> Right click on the Project --> Go to Properties --> Go to Web tab --> See the Servers --> click on radio button "USe Visual Studio Developtment Server"

I hope this will help you.

Sort array of objects by object fields

If you need local based string comparison, you can use strcoll instead of strcmp.

Remeber to first use setlocale with LC_COLLATE to set locale information if needed.

  usort($your_data,function($a,$b){
    setlocale (LC_COLLATE, 'pl_PL.UTF-8'); // Example of Polish language collation
    return strcoll($a->name,$b->name);
  });

typedef fixed length array

You want

typedef char type24[3];

C type declarations are strange that way. You put the type exactly where the variable name would go if you were declaring a variable of that type.

Call a function from another file?

Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error. So my solution was importing like below

from . import filename # without .py  

inside my first file I have defined function fun like below

# file name is firstFile.py
def fun():
  print('this is fun')

inside the second file lets say I want to call the function fun

from . import firstFile

def secondFunc():
   firstFile.fun() # calling `fun` from the first file

secondFunc() # calling the function `secondFunc` 

ORA-00060: deadlock detected while waiting for resource

You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.

I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10), I'd use TRUNC(n/10) which mean that each slave worked on a contiguous set of data.

There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.

Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Use

export LD_LIBRARY_PATH="/path/to/library/"

in your .bashrc otherwise, it'll only be available to bash and not any programs you start.

Try -R/path/to/library/ flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.

EDIT: Looks like -R is Solaris only, and you're on Linux.

An alternate way would be to add the path to /etc/ld.so.conf and run ldconfig. Note that this is a global change that will apply to all dynamically linked binaries.

What are MVP and MVC and what is the difference?

Model-View-Presenter

In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.

MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

Two primary variations

Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.

  • Pro: maximum testability surface; clean separation of the View and Model
  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.

Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.

  • Pro: by leveraging data binding the amount of code is reduced.
  • Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

Model-View-Controller

In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:

    Action in the View
        -> Call to Controller
        -> Controller Logic
        -> Controller returns the View.

One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.

Presentation Model

One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.

There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns

Best C# API to create PDF

I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.

Eclipse: The declared package does not match the expected package

Suppose your project has a package like package name1.name2.name3.name4 (declared package)

Your package explorer shows
package top level named name1.name2
sub packages named name3.name4

You will have errors because Eclipse extracts the package name from the file directory structure on disk starting at the point you import from.

My case was a bit more involved, perhaps because I was using a symbolic link to a folder outside my workspace.

I first tried Build Path.Java Build Path.Source Tab.Link Source Button.Browse to the folder before name1 in your package.Folder-name as you like (i think). But had issues.

Then I removed the folder from the build path and tried File > Import... > General > File System > click Next > From Directory > Browse... to folder above name1 > click Advanced button > check Create links in workspace > click Finish button.

Copy data from one column to other column (which is in a different table)

Now it's more easy with management studio 2016.

Using SQL Server Management Studio

To copy data from one table to another

1.Open the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design.

2.Click the tab for the table with the columns you want to copy and select those columns.

3.From the Edit menu, click Copy.

4.Open a new Query Editor window.

5.Right-click the Query Editor, and then click Design Query in Editor.

6.In the Add Table dialog box, select the source and destination table, click Add, and then close the Add Table dialog box.

7.Right-click an open area of the the Query Editor, point to Change Type, and then click Insert Results.

8.In the Choose Target Table for Insert Results dialog box, select the destination table.

9.In the upper portion of the Query Designer, click the source column in the source table.

10.The Query Designer has now created an INSERT query. Click OK to place the query into the original Query Editor window.

11.Execute the query to insert the data from the source table to the destination table.

For More Information https://docs.microsoft.com/en-us/sql/relational-databases/tables/copy-columns-from-one-table-to-another-database-engine

Why do I get "MismatchSenderId" from GCM server side?

Please run below script in your terminal

curl -X POST \
-H "Authorization: key=  write here api_key" \
-H "Content-Type: application/json" \
-d '{ 
"registration_ids": [ 
"write here reg_id generated by gcm"
], 
"data": { 
"message": "Manual push notification from Rajkumar"
},
"priority": "high"
}' \
https://android.googleapis.com/gcm/send

it will give the message if it is succeeded or failed

How to change the default charset of a MySQL table?

If someone is searching for a complete solution for changing default charset for all database tables and converting the data, this could be one:

DELIMITER $$

CREATE PROCEDURE `exec_query`(IN sql_text VARCHAR(255))
BEGIN
  SET @tquery = `sql_text`;
  PREPARE `stmt` FROM @tquery;
  EXECUTE `stmt`;
  DEALLOCATE PREPARE `stmt`;
END$$

CREATE PROCEDURE `change_character_set`(IN `charset` VARCHAR(64), IN `collation` VARCHAR(64))
BEGIN
DECLARE `done` BOOLEAN DEFAULT FALSE;
DECLARE `tab_name` VARCHAR(64);
DECLARE `charset_cursor` CURSOR FOR 
    SELECT `table_name` FROM `information_schema`.`tables`
    WHERE `table_schema` = DATABASE() AND `table_type` = 'BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = TRUE;

SET foreign_key_checks = 0;
OPEN `charset_cursor`;
`change_loop`: LOOP
FETCH `charset_cursor` INTO `tab_name`;
IF `done` THEN
    LEAVE `change_loop`;
END IF;
CALL `exec_query`(CONCAT(
  'ALTER TABLE `',
  tab_name,
  '` CONVERT TO CHARACTER SET ',
  QUOTE(charset),
  ' COLLATE ',
  QUOTE(collation),
  ';'
));
CALL `exec_query`(CONCAT('REPAIR TABLE `', tab_name, '`;'));
CALL `exec_query`(CONCAT('OPTIMIZE TABLE `', tab_name, '`;'));
END LOOP `change_loop`;
CLOSE `charset_cursor`;
SET foreign_key_checks = 1;
END$$

DELIMITER ;

You can place this code inside the file e.g. chg_char_set.sql and execute it e.g. by calling it from MySQL terminal:

SOURCE ~/path-to-the-file/chg_char_set.sql

Then call defined procedure with desired input parameters e.g.

CALL change_character_set('utf8mb4', 'utf8mb4_bin');

Once you've tested the results, you can drop those stored procedures:

DROP PROCEDURE `change_character_set`;
DROP PROCEDURE `exec_query`;

"SSL certificate verify failed" using pip to install packages

I had same issue. I was trying to install mysqlclient for my Django project.

In my case the system date/time wasn't up-to date (Windows 8). That's causing the error. So, updated my system date time and ran the command pip install mysqlclient again. And it did the work.

Hope this would be helpful for those people who're executing all the commands out there (suggesting in other answers) without checking their system date/time.

How do you put an image file in a json object?

Use data URL scheme: https://en.wikipedia.org/wiki/Data_URI_scheme

In this case you use that string directly in html : <img src="data:image/png;base64,iVBOR....">

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Display a tooltip over a button using Windows Forms

The ToolTip is a single WinForms control that handles displaying tool tips for multiple elements on a single form.

Say your button is called MyButton.

  1. Add a ToolTip control (under Common Controls in the Windows Forms toolbox) to your form.
  2. Give it a name - say MyToolTip
  3. Set the "Tooltip on MyToolTip" property of MyButton (under Misc in the button property grid) to the text that should appear when you hover over it.

The tooltip will automatically appear when the cursor hovers over the button, but if you need to display it programmatically, call

MyToolTip.Show("Tooltip text goes here", MyButton);

in your code to show the tooltip, and

MyToolTip.Hide(MyButton);

to make it disappear again.

Usage of \b and \r in C

The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.

how to send multiple data with $.ajax() jquery

var CommentData= "u_id=" + $(this).attr("u_id") + "&post_id=" + $(this).attr("p_id") + "&comment=" + $(this).val();

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

Kafka consumer list

I realize that this question is nearly 4 years old now. Much has changed in Kafka since then. This is mentioned above, but only in small print, so I write this for users who stumble over this question as late as I did.

  1. Offsets by default are now stored in a Kafka Topic (not in Zookeeper any more), see Offsets stored in Zookeeper or Kafka?
  2. There's a kafka-consumer-groups utility which returns all the information, including the offset of the topic and partition, of the consumer, and even the lag (Remark: When you ask for the topic's offset, I assume that you mean the offsets of the partitions of the topic). In my Kafka 2.0 test cluster:
kafka-consumer-groups --bootstrap-server kafka:9092 --describe
    --group console-consumer-69763 Consumer group 'console-consumer-69763' has no active members.

TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID     HOST            CLIENT-ID
pytest          0          5               6               1               -               -               -
``


How to avoid "Permission denied" when using pip with virtualenv

In my case, I was using mkvirtualenv, but didn't tell it I was going to be using python3. I got this error:

mkvirtualenv hug
pip3 install hug -U

....
error: could not create '/usr/lib/python3.4/site-packages': Permission denied

It worked after specifying python3:

mkvirtualenv --python=/usr/bin/python3 hug
pip3 install hug -U

Convert multidimensional array into single array

For this particular case, this'll do:

$array = array_map('current', $array[0]);

It's basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.

SQL Server: Difference between PARTITION BY and GROUP BY

As of my understanding Partition By is almost identical to Group By, but with the following differences:

That group by actually groups the result set returning one row per group, which results therefore in SQL Server only allowing in the SELECT list aggregate functions or columns that are part of the group by clause (in which case SQL Server can guarantee that there are unique results for each group).

Consider for example MySQL which allows to have in the SELECT list columns that are not defined in the Group By clause, in which case one row is still being returned per group, however if the column doesn't have unique results then there is no guarantee what will be the output!

But with Partition By, although the results of the function are identical to the results of an aggregate function with Group By, still you are getting the normal result set, which means that one is getting one row per underlying row, and not one row per group, and because of this one can have columns that are not unique per group in the SELECT list.

So as a summary, Group By would be best when needs an output of one row per group, and Partition By would be best when one needs all the rows but still wants the aggregate function based on a group.

Of course there might also be performance issues, see http://social.msdn.microsoft.com/Forums/ms-MY/transactsql/thread/0b20c2b5-1607-40bc-b7a7-0c60a2a55fba.

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

set date in input type date

I usually create these two helper functions when using date inputs:

// date is expected to be a date object (e.g., new Date())
const dateToInput = date =>
  `${date.getFullYear()
  }-${('0' + (date.getMonth() + 1)).slice(-2)
  }-${('0' + date.getDate()).slice(-2)
  }`;

// str is expected in yyyy-mm-dd format (e.g., "2017-03-14")
const inputToDate = str => new Date(str.split('-'));

You can then set the date input value as:

$('#datePicker').val(dateToInput(new Date()));

And retrieve the selected value like so

const dateVal = inputToDate($('#datePicker').val())

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

Printing *s as triangles in Java?

1) Normal triangle

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=n-i;j++)
         {

             System.out.print(" ");
         }

         for(int k=0;k<=2*i;k++)
         {
         System.out.print("*");
         }

         System.out.println("\n");

     }

     }

2) right angle triangle

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=n-i;j++)
         {

             System.out.print(" ");
         }

         for(int k=0;k<=i;k++)
         {
         System.out.print("*");
         }

         System.out.println("\n");

     }

     }


}

     }

3) Left angle triangle

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=i;j++)
         {

             System.out.print("*");
         }

         System.out.println("\n");

     }

     }


}

How to delete an element from a Slice in Golang

No need to check every single element unless you care contents and you can utilize slice append. try it out

pos := 0
arr := []int{1, 2, 3, 4, 5, 6, 7, 9}
fmt.Println("input your position")
fmt.Scanln(&pos)
/* you need to check if negative input as well */
if (pos < len(arr)){
    arr = append(arr[:pos], arr[pos+1:]...)
} else {
    fmt.Println("position invalid")
}

How to download PDF automatically using js?

  1. for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf

e.g. you're using php and $filepath contains pdf file path.

so you can write javascript like to to emulate download dialog box.

<script language="javascript">
    window.location.href = '<?php echo $filepath; ?>';
</script

Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.

Tomcat 8 Maven Plugin for Java 8

Since November 2017, one can use tomcat8-maven-plugin:

<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>2.2</version>
</dependency>

Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:

<pluginRepositories>
    <pluginRepository>
        <id>icm</id>
        <name>Spring Framework Milestone Repository</name>
        <url>http://maven.icm.edu.pl/artifactory/repo</url>
    </pluginRepository>
</pluginRepositories>

What is a good Hash Function?

There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean.

Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider all information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.

Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste.

This is actually one of the cases where I advise to read what Knuth has to say in The Art of Computer Programming, vol. 3. Another good read is Julienne Walker's The Art of Hashing.

How do I do a Date comparison in Javascript?

new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()

MySQL - how to front pad zip code with "0"?

You need to decide the length of the zip code (which I believe should be 5 characters long). Then you need to tell MySQL to zero-fill the numbers.

Let's suppose your table is called mytable and the field in question is zipcode, type smallint. You need to issue the following query:

ALTER TABLE mytable CHANGE `zipcode` `zipcode`
    MEDIUMINT( 5 ) UNSIGNED ZEROFILL NOT NULL;

The advantage of this method is that it leaves your data intact, there's no need to use triggers during data insertion / updates, there's no need to use functions when you SELECT the data and that you can always remove the extra zeros or increase the field length should you change your mind.

How to put two divs side by side

This is just a simple(not-responsive) HTML/CSS translation of the wireframe you provided.

enter image description here

HTML

<div class="container">

  <header>
    <div class="logo">Logo</div>
    <div class="menu">Email/Password</div>
  </header>

  <div class="first-box">
    <p>Video Explaning Site</p>
  </div>

  <div class="second-box">
    <p>Sign up Info</p>
  </div>

  <footer>
    <div>Website Info</div>
  </footer>

</div>

CSS

.container {
  width:900px; 
  height: 150px;
}

header {
  width:900px; 
  float:left; 
  background: pink; 
  height: 50px;
}

.logo {
  float: left;
  padding: 15px
}

.menu {
  float: right;
  padding: 15px
}

.first-box {
  width:300px; 
  float:left; 
  background: green; 
  height: 150px;
  margin: 50px
}

.first-box p {
  color: #ffffff;
  padding-left: 80px;
  padding-top: 50px;
}

.second-box {
  width:300px; 
  height: 150px; 
  float:right; 
  background: blue;
  margin: 50px
}

.second-box p {
  color: #ffffff;
  padding-left: 110px;
  padding-top: 50px;
}

footer {
  width:900px; 
  float:left; 
  background: black; 
  height: 50px;
  color: #ffffff;
}

footer div {
  padding: 15px;
}

Automatically accept all SDK licences

If you are using Flutter just run:

flutter doctor --android-licenses 

And accept all the licenses needed.

What is the difference between Left, Right, Outer and Inner Joins?

Simple Example: Let's say you have a Students table, and a Lockers table. In SQL, the first table you specify in a join, Students, is the LEFT table, and the second one, Lockers, is the RIGHT table.

Each student can be assigned to a locker, so there is a LockerNumber column in the Student table. More than one student could potentially be in a single locker, but especially at the beginning of the school year, you may have some incoming students without lockers and some lockers that have no students assigned.

For the sake of this example, let's say you have 100 students, 70 of which have lockers. You have a total of 50 lockers, 40 of which have at least 1 student and 10 lockers have no student.

INNER JOIN is equivalent to "show me all students with lockers".
Any students without lockers, or any lockers without students are missing.
Returns 70 rows

LEFT OUTER JOIN would be "show me all students, with their corresponding locker if they have one".
This might be a general student list, or could be used to identify students with no locker.
Returns 100 rows

RIGHT OUTER JOIN would be "show me all lockers, and the students assigned to them if there are any".
This could be used to identify lockers that have no students assigned, or lockers that have too many students.
Returns 80 rows (list of 70 students in the 40 lockers, plus the 10 lockers with no student)

FULL OUTER JOIN would be silly and probably not much use.
Something like "show me all students and all lockers, and match them up where you can"
Returns 110 rows (all 100 students, including those without lockers. Plus the 10 lockers with no student)

CROSS JOIN is also fairly silly in this scenario.
It doesn't use the linked lockernumber field in the students table, so you basically end up with a big giant list of every possible student-to-locker pairing, whether or not it actually exists.
Returns 5000 rows (100 students x 50 lockers). Could be useful (with filtering) as a starting point to match up the new students with the empty lockers.

How to filter array when object key value is in array

In case you have key value pairs in your input array, I used:

.filter(
          this.multi_items[0] != null && store.state.isSearchBox === false
            ? item =>
                _.map(this.multi_items, "value").includes(item["wijknaam"])
            : item => item["wijknaam"].includes("")
        );

where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]

_.map is a lodash function.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

Date only from TextBoxFor()

Don't be afraid of using raw HTML.

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

When I drag files in, the "Add to targets" box seems to be un-ticked by default. If I leave it un-ticked then I have the problem described. Fix it by deleting the files then dragging them back in but making sure to tick "Add to targets". enter image description here

Showing line numbers in IPython/Jupyter Notebooks

Was looking for this: Shift-L in JupyterLab 1.0.0

Delegation: EventEmitter or Observable in Angular

You can use either:

  1. Behaviour Subject:

BehaviorSubject is a type of subject, a subject is a special type of observable which can act as observable and observer you can subscribe to messages like any other observable and upon subscription, it returns the last value of the subject emitted by the source observable:

Advantage: No Relationship such as parent-child relationship required to pass data between components.

NAV SERVICE

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  private navSubject$ = new BehaviorSubject<number>(0);

  constructor() {  }

  // Event New Item Clicked
  navItemClicked(navItem: number) {
    this.navSubject$.next(number);
  }

 // Allowing Observer component to subscribe emitted data only
  getNavItemClicked$() {
   return this.navSubject$.asObservable();
  }
}

NAVIGATION COMPONENT

@Component({
  selector: 'navbar-list',
  template:`
    <ul>
      <li><a (click)="navItemClicked(1)">Item-1 Clicked</a></li>
      <li><a (click)="navItemClicked(2)">Item-2 Clicked</a></li>
      <li><a (click)="navItemClicked(3)">Item-3 Clicked</a></li>
      <li><a (click)="navItemClicked(4)">Item-4 Clicked</a></li>
    </ul>
})
export class Navigation {
  constructor(private navService:NavService) {}
  navItemClicked(item: number) {
    this.navService.navItemClicked(item);
  }
}

OBSERVING COMPONENT

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  itemClickedSubcription:any

  constructor(private navService:NavService) {}
  ngOnInit() {

    this.itemClickedSubcription = this.navService
                                      .getNavItemClicked$
                                      .subscribe(
                                        item => this.selectedNavItem(item)
                                       );
  }
  selectedNavItem(item: number) {
    this.item = item;
  }

  ngOnDestroy() {
    this.itemClickedSubcription.unsubscribe();
  }
}

Second Approach is Event Delegation in upward direction child -> parent

  1. Using @Input and @Output decorators parent passing data to child component and child notifying parent component

e.g Answered given by @Ashish Sharma.

How to compile and run C/C++ in a Unix console/Mac terminal?

Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

Using @property versus getters and setters

Prefer properties. It's what they're there for.

The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.

The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

All the other answers didn't work for me. (including cors package, or setting headers through middleware)

For socket.io 3^ this worked without any extra packages.

const express = require('express');
const app = express();

const server = require('http').createServer(app);
const io = require('socket.io')(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

How can I create a marquee effect?

With a small change of the markup, here's my approach (I've just inserted a span inside the paragraph):

_x000D_
_x000D_
.marquee {
  width: 450px;
  margin: 0 auto;
  overflow: hidden;
  box-sizing: border-box;
}

.marquee span {
  display: inline-block;
  width: max-content;

  padding-left: 100%;
  /* show the marquee just outside the paragraph */
  will-change: transform;
  animation: marquee 15s linear infinite;
}

.marquee span:hover {
  animation-play-state: paused
}


@keyframes marquee {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-100%, 0); }
}


/* Respect user preferences about animations */

@media (prefers-reduced-motion: reduce) {
  .marquee span {
    animation-iteration-count: 1;
    animation-duration: 0.01; 
    /* instead of animation: none, so an animationend event is 
     * still available, if previously attached.
     */
    width: auto;
    padding-left: 0;
  }
}
_x000D_
<p class="marquee">
   <span>
       When I had journeyed half of our life's way, I found myself
       within a shadowed forest, for I had lost the path that 
       does not stray. – (Dante Alighieri, <i>Divine Comedy</i>. 
       1265-1321)
   </span>
   </p>
_x000D_
_x000D_
_x000D_


No hardcoded values — dependent on paragraph width — have been inserted.

The animation applies the CSS3 transform property (use prefixes where needed) so it performs well.

If you need to insert a delay just once at the beginning then also set an animation-delay. If you need instead to insert a small delay at every loop then try to play with an higher padding-left (e.g. 150%)

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

If swfobject won't suffice, or you need to create something a little more bespoke, try this:

var hasFlash = false;
try {
    hasFlash = Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
} catch(exception) {
    hasFlash = ('undefined' != typeof navigator.mimeTypes['application/x-shockwave-flash']);
}

It works with 7 and 8.

Maven skip tests

During maven compilation you can skip test execution by adding following plugin in pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration>
         <skipTests>true</skipTests>
    </configuration>
</plugin>

How do I create a sequence in MySQL?

This is a solution suggested by the MySQl manual:

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:

Create a table to hold the sequence counter and initialize it:

    mysql> CREATE TABLE sequence (id INT NOT NULL);
    mysql> INSERT INTO sequence VALUES (0);

Use the table to generate sequence numbers like this:

    mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
    mysql> SELECT LAST_INSERT_ID();

The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.

You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

How do you create a UIImage View Programmatically - Swift

You can use above in one line.

  let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)

Laravel Unknown Column 'updated_at'

Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put

public $timestamps = false;

Timestamps are nicely explained on official Laravel page:

By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.