Programs & Examples On #Jackrabbit

The Apache Jackrabbit™ content repository is a fully conforming implementation of the Content Repository for Java Technology API (JCR, specified in JSR 170 and 283). A content repository is a hierarchical content store with support for structured and unstructured content, full text search, versioning, transactions, observation, and more.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

How to round the double value to 2 decimal points?

double RoundTo2Decimals(double val) {
            DecimalFormat df2 = new DecimalFormat("###.##");
        return Double.valueOf(df2.format(val));
}

How to get length of a list of lists in python

This saves the data in a list of lists.

text = open("filetest.txt", "r")
data = [ ]
for line in text:
    data.append( line.strip().split() )

print "number of lines ", len(data)
print "number of columns ", len(data[0])

print "element in first row column two ", data[0][1]

How to color the Git console?

As noted by @VonC, color.ui defaults to auto since Git 1.8.4


From the Unix & Linux Stackexchange question How to colorize output of git? and the answer by @Evgeny:

git config --global color.ui auto

The color.ui is a meta configuration that includes all the various color.* configurations available with git commands. This is explained in-depth in git help config.

So basically it's easier and more future proof than setting the different color.* settings separately.

In-depth explanation from the git config documentation:

color.ui: This variable determines the default value for variables such as color.diff and color.grep that control the use of color per command family. Its scope will expand as more commands learn configuration to set a default for the --color option. Set it to always if you want all output not intended for machine consumption to use color, to true or auto if you want such output to use color when written to the terminal, or to false or never if you prefer git commands not to use color unless enabled explicitly with some other configuration or the --color option.

mysql extract year from date format

try this code:

SELECT DATE_FORMAT(FROM_UNIXTIME(field), '%Y') FROM table

Java String to JSON conversion

Instead of JSONObject , you can use ObjectMapper to convert java object to json string

ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);

How to encode the filename parameter of Content-Disposition header in HTTP?

The following document linked from the draft RFC mentioned by Jim in his answer further addresses the question and definitely worth a direct note here:

Test Cases for HTTP Content-Disposition header and RFC 2231/2047 Encoding

error code 1292 incorrect date value mysql

With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.

If you want to allow it, you have to update your my.cnf like:

sudo nano /etc/mysql/my.cnf

find

[mysqld]

Add after:

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Restart mysql service:

sudo service mysql restart

Done!

Component based game engine design

Update 2013-01-07: If you want to see a good mix of component-based game engine with the (in my opinion) superior approach of reactive programming take a look at the V-Play engine. It very well integrates QTs QML property binding functionality.

We did some research on CBSE in games at our university and I collected some material over the years:

CBSE in games literature:

  • Game Engine Architecture
  • Game Programming Gems 4: A System for Managin Game Entities Game
  • Game Programming Gems 5: Component Based Object Management
  • Game Programming Gems 5: A Generic Component Library
  • Game Programming Gems 6: Game Object Component System
  • Object-Oriented Game Development
  • Architektur des Kerns einer Game-Engine und Implementierung mit Java (german)

A very good and clean example of a component-based game-engine in C# is the Elephant game framework.

If you really want to know what components are read: Component-based Software Engineering! They define a component as:

A software component is a software element that conforms to a component model and can be independently deployed and composed without modification according to a composition standard.

A component model defines specific interaction and composition standards. A component model implementation is the dedicated set of executable software elements required to support the execution of components that conform to the model.

A software component infrastructure is a set of interacting software components designed to ensure that a software system or subsystem constructed using those components and interfaces will satisfy clearly defined performance specifications.

My opinions after 2 years of experience with CBSE in games thought are that object-oriented programming is simply a dead-end. Remember my warning as you watch your components become smaller and smaller, and more like functions packed in components with a lot of useless overhead. Use functional-reactive programming instead. Also take a look at my fresh blog post (which lead me to this question while writing it :)) about Why I switched from component-based game engine architecture to FRP.

CBSE in games papers:

CBSE in games web-links (sorted by relevancy):

How to create a timer using tkinter?

The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:

from tkinter import *
import time


def update_clock():
    timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
                  font='Times 25')  # change the text of the time_label according to the current time
    root.after(100, update_clock)  # reschedule update_clock function to update time_label every 100 ms

root = Tk()  # create the root window
timer_label = Label(root, justify='center')  # create the label for timer
timer_label.pack()  # show the timer_label using pack geometry manager
root.after(0, update_clock)  # schedule update_clock function first call
root.mainloop()  # start the root window mainloop

how to run the command mvn eclipse:eclipse

I don't think one needs it any more. The latest versions of Eclipse have Maven plugin enabled. So you will just need to import a Maven project into Eclipse and no more as an existing project. Eclipse will create the needed .project, .settings, .classpath files based on your pom.xml and environment settings (installed Java version, etc.) . The earlier versions of Eclipse needed to have run the command mvn eclipse:eclipse which produced the same result.

When is the finalize() method called in Java?

Java allows objects to implement a method called finalize() that might get called.

finalize() method gets called if the garbage collector tries to collect the object.

If the garbage collector doesn't run, the method doesn't get called.

If the garbage collector fails to collect the object and tries to run it again, the method doesn't get called in the second time.

In practice, you are highly unlikely to use it in real projects.

Just keep in mind that it might not get called and that it definitely won't be called twice. The finalize() method could run zero or one time.

In the following code, finalize() method produces no output when we run it since the program exits before there is any need to run the garbage collector.

Source

File Upload using AngularJS

The easiest is to use HTML5 API, namely FileReader

HTML is pretty straightforward:

<input type="file" id="file" name="file"/>
<button ng-click="add()">Add</button>

In your controller define 'add' method:

$scope.add = function() {
    var f = document.getElementById('file').files[0],
        r = new FileReader();

    r.onloadend = function(e) {
      var data = e.target.result;
      //send your binary data via $http or $resource or do anything else with it
    }

    r.readAsBinaryString(f);
}

Browser Compatibility

Desktop Browsers

Edge 12, Firefox(Gecko) 3.6(1.9.2), Chrome 7, Opera* 12.02, Safari 6.0.2

Mobile Browsers

Firefox(Gecko) 32, Chrome 3, Opera* 11.5, Safari 6.1

Note : readAsBinaryString() method is deprecated and readAsArrayBuffer() should be used instead.

How do I convert a String to a BigInteger?

Instead of using valueOf(long) and parse(), you can directly use the BigInteger constructor that takes a string argument:

BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");

That should give you the desired value.

NoClassDefFoundError - Eclipse and Android

I have changed the order of included projects (Eclipse / Configure Build Path / Order and Export). I have moved my two dependent projects to the top of the "Order and Export" list. It solved the problem "NoClassDefFoundError".

It is strange for me. I didn't heard about the importance of the order of included libraries and projects. Android + Eclipse is fun :)

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

How do you make div elements display inline?

Try writing it like this:

_x000D_
_x000D_
div { border: 1px solid #CCC; }
_x000D_
    <div style="display: inline">a</div>_x000D_
    <div style="display: inline">b</div>_x000D_
    <div style="display: inline">c</div>
_x000D_
_x000D_
_x000D_

Using global variables between files?

The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

# settings.py

def init():
    global myList
    myList = []

Next, your subfile can import globals:

# subfile.py

import settings

def stuff():
    settings.myList.append('hey')

Note that subfile does not call init()— that task belongs to main.py:

# main.py

import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result

This way, you achieve your objective while avoid initializing global variables more than once.

Get name of property as a string

Using GetMemberInfo from here: Retrieving Property name from lambda expression you can do something like this:

RemoteMgr.ExposeProperty(() => SomeClass.SomeProperty)

public class SomeClass
{
    public static string SomeProperty
    {
        get { return "Foo"; }
    }
}

public class RemoteMgr
{
    public static void ExposeProperty<T>(Expression<Func<T>> property)
    {
        var expression = GetMemberInfo(property);
        string path = string.Concat(expression.Member.DeclaringType.FullName,
            ".", expression.Member.Name);
        // Do ExposeProperty work here...
    }
}

public class Program
{
    public static void Main()
    {
        RemoteMgr.ExposeProperty("SomeSecret", () => SomeClass.SomeProperty);
    }
}

How to read first N lines of a file?


fname = input("Enter file name: ")
num_lines = 0

with open(fname, 'r') as f: #lines count
    for line in f:
        num_lines += 1

num_lines_input = int (input("Enter line numbers: "))

if num_lines_input <= num_lines:
    f = open(fname, "r")
    for x in range(num_lines_input):
        a = f.readline()
        print(a)

else:
    f = open(fname, "r")
    for x in range(num_lines_input):
        a = f.readline()
        print(a)
        print("Don't have", num_lines_input, " lines print as much as you can")


print("Total lines in the text",num_lines)

Copy Data from a table in one Database to another separate database

This works successfully.

INSERT INTO DestinationDB.dbo.DestinationTable (col1,col1)
 SELECT Src-col1,Src-col2 FROM SourceDB.dbo.SourceTable

The system cannot find the file specified in java

Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.

Git Clone: Just the files, please?

The git command that would be the closest from what you are looking for would by git archive.
See backing up project which uses git: it will include in an archive all files (including submodules if you are using the git-archive-all script)

You can then use that archive anywhere, giving you back only files, no .git directory.

git archive --remote=<repository URL> | tar -t

If you need folders and files just from the first level:

git archive --remote=<repository URL> | tar -t --exclude="*/*"

To list only first-level folders of a remote repo:

git archive --remote=<repository URL> | tar -t --exclude="*/*" | grep "/"

Note: that does not work for GitHub (not supported)

So you would need to clone (shallow to quicken the clone step), and then archive locally:

git clone --depth=1 [email protected]:xxx/yyy.git
cd yyy
git archive --format=tar aTag -o aTag.tar

Another option would be to do a shallow clone (as mentioned below), but locating the .git folder elsewhere.

git --git-dir=/path/to/another/folder.git clone --depth=1 /url/to/repo

The repo folder would include only the file, without .git.

Note: git --git-dir is an option of the command git, not git clone.


Update with Git 2.14.X/2.15 (Q4 2017): it will make sure to avoid adding empty folders.

"git archive", especially when used with pathspec, stored an empty directory in its output, even though Git itself never does so.
This has been fixed.

See commit 4318094 (12 Sep 2017) by René Scharfe (``).
Suggested-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 62b1cb7, 25 Sep 2017)

archive: don't add empty directories to archives

While git doesn't track empty directories, git archive can be tricked into putting some into archives.
While that is supported by the object database, it can't be represented in the index and thus it's unlikely to occur in the wild.

As empty directories are not supported by git, they should also not be written into archives.
If an empty directory is really needed then it can be tracked and archived by placing an empty .gitignore file in it.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 30vh;
object-fit: contain;
}

Contain will help in getting Complete Image displayed inside Card.

Adjust height "30vh" according to your need!

C# find highest array value and index

This can be done with a bodiless for loop, if we're heading towards golf ;)

//a is the array


int mi = a.Length - 1;
for (int i=-1; ++i<a.Length-1; mi=a[mi]<a[i]?i:mi) ;

The check of ++i<a.Length-1 omits checking the last index. We don't mind this if we set it up as if the max index is the last index to start with.. When the loop runs for the other elements it will finish and one or the other thing is true:

  • we found a new max value and hence a new max index mi
  • the last index was the max value all along, so we didn't find a new mi, and we stuck with the initial mi

The real work is done by the post-loop modifiers:

  • is the max value (a[mi] i.e. array indexed by mi) we found so far, less than the current item?
    • yes, then store a new mi by remembering i,
    • no then store the existing mi (no-op)

At the end of the operation you have the index at which the max is to be found. Logically then the max value is a[mi]

I couldn't quite see how the "find max and index of max" really needed to track the max value too, given that if you have an array, and you know the index of the max value, the actual value of the max value is a trivial case of using the index to index the array..

Putting a password to a user in PhpMyAdmin in Wamp

Search your installation of PhpMyAdmin for a file called Documentation.txt. This describes how to create a file called config.inc.php and how you can configure the username and password.

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Multiple inheritance for an anonymous class

I guess nobody understood the question. I guess what this guy wanted was something like this:

return new (class implements MyInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }
});

because this would allow things like multiple interface implementations:

return new (class implements MyInterface, AnotherInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }

    @Override
    public void anotherInterfaceMethod() { /*do something*/ }
});

this would be really nice indeed; but that's not allowed in Java.

What you can do is use local classes inside method blocks:

public AnotherInterface createAnotherInterface() {
    class LocalClass implements MyInterface, AnotherInterface {
        @Override
        public void myInterfaceMethod() { /*do something*/ }

        @Override
        public void anotherInterfaceMethod() { /*do something*/ }
    }
    return new LocalClass();
}

PDF Editing in PHP?

<?php

//getting new instance
$pdfFile = new_pdf();

PDF_open_file($pdfFile, " ");

//document info
pdf_set_info($pdfFile, "Auther", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Creator", "Ahmed Elbshry");
pdf_set_info($pdfFile, "Title", "PDFlib");
pdf_set_info($pdfFile, "Subject", "Using PDFlib");

//starting our page and define the width and highet of the document
pdf_begin_page($pdfFile, 595, 842);

//check if Arial font is found, or exit
if($font = PDF_findfont($pdfFile, "Arial", "winansi", 1)) {
    PDF_setfont($pdfFile, $font, 12);
} else {
    echo ("Font Not Found!");
    PDF_end_page($pdfFile);
    PDF_close($pdfFile);
    PDF_delete($pdfFile);
    exit();
}

//start writing from the point 50,780
PDF_show_xy($pdfFile, "This Text In Arial Font", 50, 780);
PDF_end_page($pdfFile);
PDF_close($pdfFile);

//store the pdf document in $pdf
$pdf = PDF_get_buffer($pdfFile);
//get  the len to tell the browser about it
$pdflen = strlen($pdfFile);

//telling the browser about the pdf document
header("Content-type: application/pdf");
header("Content-length: $pdflen");
header("Content-Disposition: inline; filename=phpMade.pdf");
//output the document
print($pdf);
//delete the object
PDF_delete($pdfFile);
?>

How can I get the current page's full URL on a Windows/IIS server?

The posttitle part of the URL is after your index.php file, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

This is very easy by import repository feature Login to github.com,

Side of profile picture you will find + button click on that then there will be option to import repository. you will find page like this. enter image description here Your old repository’s clone URL is required which is gitlab repo url in your case. then select Owner and then type name for this repo and click to begin import button.

Jenkins: Is there any way to cleanup Jenkins workspace?

There is a way to cleanup workspace in Jenkins. You can clean up the workspace before build or after build.

First, install Workspace Cleanup Plugin.

To clean up the workspace before build: Under Build Environment, check the box that says Delete workspace before build starts.

To clean up the workspace after the build: Under the heading Post-build Actions select Delete workspace when build is done from the Add Post-build Actions drop down menu.

SimpleDateFormat parsing date with 'Z' literal

I provide another answer that I found by api-client-library by Google

try {
    DateTime dateTime = DateTime.parseRfc3339(date);
    dateTime = new DateTime(new Date(dateTime.getValue()), TimeZone.getDefault());
    long timestamp = dateTime.getValue();  // get date in timestamp
    int timeZone = dateTime.getTimeZoneShift();  // get timezone offset
} catch (NumberFormatException e) {
    e.printStackTrace();
}

Installation guide,
https://developers.google.com/api-client-library/java/google-api-java-client/setup#download

Here is API reference,
https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/DateTime

Source code of DateTime Class,
https://github.com/google/google-http-java-client/blob/master/google-http-client/src/main/java/com/google/api/client/util/DateTime.java

DateTime unit tests,
https://github.com/google/google-http-java-client/blob/master/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java#L121

How to use shared memory with Linux in C

try this code sample, I tested it, source: http://www.makelinux.net/alp/035

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 

int main () 
{
  int segment_id; 
  char* shared_memory; 
  struct shmid_ds shmbuffer; 
  int segment_size; 
  const int shared_segment_size = 0x6400; 

  /* Allocate a shared memory segment.  */ 
  segment_id = shmget (IPC_PRIVATE, shared_segment_size, 
                 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); 
  /* Attach the shared memory segment.  */ 
  shared_memory = (char*) shmat (segment_id, 0, 0); 
  printf ("shared memory attached at address %p\n", shared_memory); 
  /* Determine the segment's size. */ 
  shmctl (segment_id, IPC_STAT, &shmbuffer); 
  segment_size  =               shmbuffer.shm_segsz; 
  printf ("segment size: %d\n", segment_size); 
  /* Write a string to the shared memory segment.  */ 
  sprintf (shared_memory, "Hello, world."); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Reattach the shared memory segment, at a different address.  */ 
  shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0); 
  printf ("shared memory reattached at address %p\n", shared_memory); 
  /* Print out the string from shared memory.  */ 
  printf ("%s\n", shared_memory); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Deallocate the shared memory segment.  */ 
  shmctl (segment_id, IPC_RMID, 0); 

  return 0; 
} 

Tool to Unminify / Decompress JavaScript

As an alternative (since I didn't know about jsbeautifier.org until now), I have used a bookmarklet that reenabled the decode button in Dean Edward's Packer.

I found the instructions and bookmarklet here.

here is the bookmarklet (in case the site is down)

javascript:for%20(i=0;i<document.forms.length;++i)%20{for(j=0;j<document.forms[i].elements.length;++j){document.forms[i].elements[j].removeAttribute(%22readonly%22);document.forms[i].elements[j].removeAttribute(%22disabled%22);}}

Start HTML5 video at a particular position when loading?

WITHOUT USING JAVASCRIPT

Just add #t=[(start_time), (end_time)] to the end of your media URL. The only setback (if you want to see it that way) is you'll need to know how long your video is to indicate the end time. Example:

<video>
    <source src="splash.mp4#t=10,20" type="video/mp4">
</video>

Notes: Not supported in IE

List of all unique characters in a string?

I have an idea. Why not use the ascii_lowercase constant?

For example, running the following code:

# string module, contains constant ascii_lowercase which is all the lowercase
# letters of the English alphabet
import string
# Example value of s, a string
s = 'aaabcabccd'
# Result variable to store the resulting string
result = ''
# Goes through each letter in the alphabet and checks how many times it appears.
# If a letter appears at least oce, then it is added to the result variable
for letter in string.ascii_letters:
    if s.count(letter) >= 1:
        result+=letter

# Optional three lines to convert result variable to a list for sorting
# and then back to a string
result = list(result)
result.sort()
result = ''.join(result)

print(result)

Will print 'abcd'

There you go, all duplicates removed and optionally sorted

How do you configure an OpenFileDialog to select folders?

Better to use the FolderBrowserDialog for that.

using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
    dlg.Description = "Select a folder";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        MessageBox.Show("You selected: " + dlg.SelectedPath);
    }
}

Scroll to element on click in Angular 4

You could do it like this:

<button (click)="scroll(target)"></button>
<div #target>Your target</div>

and then in your component:

scroll(el: HTMLElement) {
    el.scrollIntoView();
}

Edit: I see comments stating that this no longer works due to the element being undefined. I created a StackBlitz example in Angular 7 and it still works. Can someone please provide an example where it does not work?

Google Maps API v3: How do I dynamically change the marker icon?

You can try this code

    <script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>

<script>

    function initialize()
    {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
                            zoom: 10,
                            mapTypeId: google.maps.MapTypeId.ROADMAP    
                         };
        map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);
        var markers = [
            ['title-1', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.120850, '<p> Hello - 1 </p>'],
            ['title-2', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.420850, '<p> Hello - 2 </p>'],
            ['title-3', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.720850, '<p> Hello - 3 </p>'],
            ['title-4', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.020850, '<p> Hello - 4 </p>'],
            ['title-5', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.320850, '<p> Hello - 5 </p>']
        ];

        var infoWindow = new google.maps.InfoWindow(), marker, i;
        var testMarker = [];
        var status = [];
        for( i = 0; i < markers.length; i++ ) 
        {
            var title = markers[i][0];
            var loan = markers[i][1];
            var lat = markers[i][2];
            var long = markers[i][3];
            var add = markers[i][4];


            var iconGreen = 'img/greenMarker.png'; //green marker
            var iconRed = 'img/redMarker.png';     //red marker

            var infoWindowContent = loan + "\n" + placeId + add;

            var position = new google.maps.LatLng(lat, long);
            bounds.extend(position);

            marker = new google.maps.Marker({
                map: map,
                title: title,
                position: position,
                icon: iconGreen
            });
            testMarker[i] = marker;
            status[i] = 1;
            google.maps.event.addListener(marker, 'click', ( function toggleBounce( i,status,testMarker) 
            {
                return function() 
                {
                    infoWindow.setContent(markers[i][1]+markers[i][4]);
                    if( status[i] === 1 )
                    {
                        testMarker[i].setIcon(iconRed);
                        status[i] = 0;

                    }
                    for( var k = 0; k <  markers.length ; k++ )
                    {
                        if(k != i)
                        {
                            testMarker[k].setIcon(iconGreen);
                            status[i] = 1;

                        }
                    }
                    infoWindow.open(map, testMarker[i]);
                }
            })( i,status,testMarker));
            map.fitBounds(bounds);
        }
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event)
        {
            this.setZoom(8);
            google.maps.event.removeListener(boundsListener);
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

</script>

<div id="mapDiv" style="width:820px; height:300px"></div>

How can I get the console logs from the iOS Simulator?

No NSLog or print content will write to system.log, which can be open by Select Simulator -> Debug -> Open System log on Xcode 11.

I figure out a way, write logs into a file and open the xx.log with Terminal.app.Then the logs will present in Terminal.app lively.

I use CocoaLumberjack achieve this.

STEP 1:

Add DDFileLogger DDOSLogger and print logs path. config() should be called when App lunch.

static func config() {
    #if DEBUG
    DDLog.add(DDOSLogger.sharedInstance) // Uses os_log
    let fileLogger: DDFileLogger = DDFileLogger() // File Logger
    fileLogger.rollingFrequency = 60 * 60 * 24 // 24 hours
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7
    DDLog.add(fileLogger)
    DDLogInfo("DEBUG LOG PATH: " + (fileLogger.currentLogFileInfo?.filePath ?? ""))
    #endif
}

STEP 2:

Replace print or NSLog with DDLogXXX.

STEP 3:

$ tail -f {path of log}

Here, message will present in Terminal.app lively.

One thing more. If there is no any message log out, make sure Environment Variables -> OS_ACTIVITY_MODE ISNOT disable.

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

CSS vertical alignment of inline/inline-block elements

Give vertical-align:top; in a & span. Like this:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/

How to convert a python numpy array to an RGB image with Opencv 2.4?

This is due to the fact that cv2 uses the type "uint8" from numpy. Therefore, you should define the type when creating the array.

Something like the following:

import numpy
import cv2

b = numpy.zeros([5,5,3], dtype=numpy.uint8)
b[:,:,0] = numpy.ones([5,5])*64
b[:,:,1] = numpy.ones([5,5])*128
b[:,:,2] = numpy.ones([5,5])*192

Rounding SQL DateTime to midnight

As @BassamMehanni mentioned, you can cast as DATE in SQL Server 2008 onwards...

SELECT
  *
FROM
  yourTable
WHERE
      dateField >= CAST(GetDate() - 6 AS DATE)
  AND dateField <  CAST(GetDate() + 1 AS DATE)

The second condition can actually be just GetDate(), but I'm showing this format as an example of Less Than DateX to avoid having to cast the dateField to a DATE as well, thus massively improving performance.


If you're on 2005 or under, you can use this...

SELECT
  *
FROM
  yourTable
WHERE
      dateField >= DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) - 6, 0)
  AND dateField <  DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) + 1, 0)

WPF User Control Parent

If you are finding this question and the VisualTreeHelper isn't working for you or working sporadically, you may need to include LogicalTreeHelper in your algorithm.

Here is what I am using:

public static T TryFindParent<T>(DependencyObject current) where T : class
{
    DependencyObject parent = VisualTreeHelper.GetParent(current);
    if( parent == null )
        parent = LogicalTreeHelper.GetParent(current);
    if( parent == null )
        return null;

    if( parent is T )
        return parent as T;
    else
        return TryFindParent<T>(parent);
}

Accessing inventory host variable in Ansible playbook

[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar

[host_group:vars]
custom_var=asdasdasd

You can access host group vars using:

{{ hostvars['host_group'].custom_var }}

If you need a specific value from specific host, you can use:

{{ hostvars[groups['host_group'][0]].node_name }}

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

How to make PopUp window in java

The same answer : JOptionpane with an example :)

package experiments;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class CreateDialogFromOptionPane {

    public static void main(final String[] args) {
        final JFrame parent = new JFrame();
        JButton button = new JButton();

        button.setText("Click me to show dialog!");
        parent.add(button);
        parent.pack();
        parent.setVisible(true);

        button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String name = JOptionPane.showInputDialog(parent,
                        "What is your name?", null);
            }
        });
    }
}

enter image description here

webpack is not recognized as a internal or external command,operable program or batch file

Maybe a clean install will fix the problem. This "command" removes all previous modules and re-installs them, perhaps while the webpack module is incompletely downloaded and installed.

npm clean-install

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

How to do IF NOT EXISTS in SQLite

How about this?

INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'

(Untested as I don't have SQLite... however this link is quite descriptive.)

Additionally, this should also work:

INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');

Search and replace a line in a file in Python

Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis

This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.

Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.

Reading the file as a single string instead of line by line allows for multiline match and replacement.

import re

def replace(file, pattern, subst):
    # Read contents from file as a single string
    file_handle = open(file, 'r')
    file_string = file_handle.read()
    file_handle.close()

    # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
    file_string = (re.sub(pattern, subst, file_string))

    # Write contents to file.
    # Using mode 'w' truncates the file.
    file_handle = open(file, 'w')
    file_handle.write(file_string)
    file_handle.close()

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

C++ callback using class member

Here's a concise version that works with class method callbacks and with regular function callbacks. In this example, to show how parameters are handled, the callback function takes two parameters: bool and int.

class Caller {
  template<class T> void addCallback(T* const object, void(T::* const mf)(bool,int))
  {
    using namespace std::placeholders; 
    callbacks_.emplace_back(std::bind(mf, object, _1, _2));
  }
  void addCallback(void(* const fun)(bool,int)) 
  {
    callbacks_.emplace_back(fun);
  }
  void callCallbacks(bool firstval, int secondval) 
  {
    for (const auto& cb : callbacks_)
      cb(firstval, secondval);
  }
private:
  std::vector<std::function<void(bool,int)>> callbacks_;
}

class Callee {
  void MyFunction(bool,int);
}

//then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`

ptr->addCallback(this, &Callee::MyFunction);

//or to add a call back to a regular function
ptr->addCallback(&MyRegularFunction);

This restricts the C++11-specific code to the addCallback method and private data in class Caller. To me, at least, this minimizes the chance of making mistakes when implementing it.

Ways to implement data versioning in MongoDB

Here's another solution using a single document for the current version and all old versions:

{
    _id: ObjectId("..."),
    data: [
        { vid: 1, content: "foo" },
        { vid: 2, content: "bar" }
    ]
}

data contains all versions. The data array is ordered, new versions will only get $pushed to the end of the array. data.vid is the version id, which is an incrementing number.

Get the most recent version:

find(
    { "_id":ObjectId("...") },
    { "data":{ $slice:-1 } }
)

Get a specific version by vid:

find(
    { "_id":ObjectId("...") },
    { "data":{ $elemMatch:{ "vid":1 } } }
)

Return only specified fields:

find(
    { "_id":ObjectId("...") },
    { "data":{ $elemMatch:{ "vid":1 } }, "data.content":1 }
)

Insert new version: (and prevent concurrent insert/update)

update(
    {
        "_id":ObjectId("..."),
        $and:[
            { "data.vid":{ $not:{ $gt:2 } } },
            { "data.vid":2 }
        ]
    },
    { $push:{ "data":{ "vid":3, "content":"baz" } } }
)

2 is the vid of the current most recent version and 3 is the new version getting inserted. Because you need the most recent version's vid, it's easy to do get the next version's vid: nextVID = oldVID + 1.

The $and condition will ensure, that 2 is the latest vid.

This way there's no need for a unique index, but the application logic has to take care of incrementing the vid on insert.

Remove a specific version:

update(
    { "_id":ObjectId("...") },
    { $pull:{ "data":{ "vid":2 } } }
)

That's it!

(remember the 16MB per document limit)

Determine installed PowerShell version

This is the top search result for "Batch file get powershell version", so I'd like to provide a basic example of how to do conditional flow in a batch file depending on the powershell version

Generic example

powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
    echo Do some fancy stuff that only powershell v5 or higher supports
) else (
    echo Functionality not support by current powershell version.
)

Real world example

powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
    rem Unzip archive automatically
    powershell Expand-Archive Compressed.zip
) else (
    rem Make the user unzip, because lazy
    echo Please unzip Compressed.zip prior to continuing...
    pause
)

Creating a comma separated list from IList<string> or IEnumerable<string>

Since I reached here while searching to join on a specific property of a list of objects (and not the ToString() of it) here's an addition to the accepted answer:

var commaDelimited = string.Join(",", students.Where(i => i.Category == studentCategory)
                                 .Select(i => i.FirstName));

android EditText - finished typing event

Better way, you can also use EditText onFocusChange listener to check whether user has done editing: (Need not rely on user pressing the Done or Enter button on Soft keyboard)

 ((EditText)findViewById(R.id.youredittext)).setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) { {
         // Validate youredittext
      }
    }
 });

Note : For more than one EditText, you can also let your class implement View.OnFocusChangeListener then set the listeners to each of you EditText and validate them as below

((EditText)findViewById(R.id.edittext1)).setOnFocusChangeListener(this);
((EditText)findViewById(R.id.edittext2)).setOnFocusChangeListener(this);

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) {
        switch (view.getId()) {
           case R.id.edittext1:
                 // Validate EditText1
                 break;
           case R.id.edittext2:
                 // Validate EditText2
                 break;
        }
      }
    }

Insert/Update/Delete with function in SQL Server

No, you cannot.

From SQL Server Books Online:

User-defined functions cannot be used to perform actions that modify the database state.

Ref.

How do I test a single file using Jest?

It can also be achieved by:

jest --findRelatedTests path/to/fileA.js

Reference (Jest CLI Options)

How can that be achieved in the Nx monorepo? Here is the answer (in directory /path/to/workspace):

npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts

Reference & more information: How to test a single Jest test file in Nx #6

Launch Pycharm from command line (terminal)

On Mac OSX

Update 2019/05 Now this can be done in the JetBrains Toolbox app. You can set it once with the Toolbox, for all of your JetBrain IDEs.


As of 2019.1 EAP, the Create Commmand Line Launcher option is not available in the Tools menu anymore. My solution is to use the following alias in my bash/zsh profile:

Make sure that you run chmod -x ...../pycharm to make the binary executable.

# in your ~/.profile or other rc file to the effect.

alias pycharm="open -a '$(ls -r /Users/geyang/Library/Application\ Support/JetBrains/Toolbox/apps/PyCharm-P/**/PyCharm*.app/Contents/MacOS/pycharm)'"

AngularJS : ng-model binding not updating when changed with jQuery

Angular doesn't know about that change. For this you should call $scope.$digest() or make the change inside of $scope.$apply():

$scope.$apply(function() { 
   // every changes goes here
   $('#selectedDueDate').val(dateText); 
});

See this to better understand dirty-checking

UPDATE: Here is an example

How to override and extend basic Django admin templates?

I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.

Assuming the standard Django project structure:

mysite-container/         # project container directory
    manage.py
    mysite/               # project package
        __init__.py
        admin.py
        apps.py
        settings.py
        urls.py
        wsgi.py
    app1/
    app2/
    ...
    static/
    templates/

Here's what you need to do:

  1. In mysite/admin.py, create a sub-class of AdminSite:

    from django.contrib.admin import AdminSite
    
    
    class CustomAdminSite(AdminSite):
        # set values for `site_header`, `site_title`, `index_title` etc.
        site_header = 'Custom Admin Site'
        ...
    
        # extend / override admin views, such as `index()`
        def index(self, request, extra_context=None):
            extra_context = extra_context or {}
    
            # do whatever you want to do and save the values in `extra_context`
            extra_context['world'] = 'Earth'
    
            return super(CustomAdminSite, self).index(request, extra_context)
    
    
    custom_admin_site = CustomAdminSite()
    

    Make sure to import custom_admin_site in the admin.py of your apps and register your models on it to display them on your customized admin site (if you want to).

  2. In mysite/apps.py, create a sub-class of AdminConfig and set default_site to admin.CustomAdminSite from the previous step:

    from django.contrib.admin.apps import AdminConfig
    
    
    class CustomAdminConfig(AdminConfig):
        default_site = 'admin.CustomAdminSite'
    
  3. In mysite/settings.py, replace django.admin.site in INSTALLED_APPS with apps.CustomAdminConfig (your custom admin app config from the previous step).

  4. In mysite/urls.py, replace admin.site.urls from the admin URL to custom_admin_site.urls

    from .admin import custom_admin_site
    
    
    urlpatterns = [
        ...
        path('admin/', custom_admin_site.urls),
        # for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)),
        ...
    ]
    
  5. Create the template you want to modify in your templates directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifying admin/index.html, create the file templates/admin/index.html.

    All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.

  6. Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.

    For example, if you wanted to keep everything as-is but wanted to override the content block (which on the index page lists the apps and their models that you registered), add the following to templates/admin/index.html:

    {% extends 'admin/index.html' %}
    
    {% block content %}
      <h1>
        Hello, {{ world }}!
      </h1>
    {% endblock %}
    

    To preserve the original contents of a block, add {{ block.super }} wherever you want the original contents to be displayed:

    {% extends 'admin/index.html' %}
    
    {% block content %}
      <h1>
        Hello, {{ world }}!
      </h1>
      {{ block.super }}
    {% endblock %}
    

    You can also add custom styles and scripts by modifying the extrastyle and extrahead blocks.

How do I get monitor resolution in Python?

And for completeness, Mac OS X

import AppKit
[(screen.frame().size.width, screen.frame().size.height)
    for screen in AppKit.NSScreen.screens()]

will give you a list of tuples containing all screen sizes (if multiple monitors present)

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

keyword not supported data source

I was getting the same problem.
but this code works good try it.

<add name="MyCon" connectionString="Server=****;initial catalog=PortalDb;user id=**;password=**;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

Adding a favicon to a static HTML page

I know its older post but still posting for someone like me. This worked for me

<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />

put your favicon icon on root directory..

What is the difference between .text, .value, and .value2?

Out of curiosity, I wanted to see how Value performed against Value2. After about 12 trials of similar processes, I could not see any significant differences in speed so I would always recommend using Value. I used the below code to run some tests with various ranges.

If anyone sees anything contrary regarding performance, please post.

Sub Trial_RUN()
    For t = 0 To 5
        TestValueMethod (True)
        TestValueMethod (False)
    Next t

End Sub




Sub TestValueMethod(useValue2 As Boolean)
Dim beginTime As Date, aCell As Range, rngAddress As String, ResultsColumn As Long
ResultsColumn = 5

'have some values in your RngAddress. in my case i put =Rand() in the cells, and then set to values
rngAddress = "A2:A399999" 'I changed this around on my sets.



With ThisWorkbook.Sheets(1)
.Range(rngAddress).Offset(0, 1).ClearContents


beginTime = Now

For Each aCell In .Range(rngAddress).Cells
    If useValue2 Then
        aCell.Offset(0, 1).Value2 = aCell.Value2 + aCell.Offset(-1, 1).Value2
    Else
        aCell.Offset(0, 1).Value = aCell.Value + aCell.Offset(-1, 1).Value
    End If

Next aCell

Dim Answer As String
 If useValue2 Then Answer = " using Value2"

.Cells(Rows.Count, ResultsColumn).End(xlUp).Offset(1, 0) = DateDiff("S", beginTime, Now) & _
            " seconds. For " & .Range(rngAddress).Cells.Count & " cells, at " & Now & Answer


End With


End Sub

enter image description here

How to have multiple CSS transitions on an element?

EDIT: I'm torn on whether to delete this post. As a matter of understanding the CSS syntax, it's good that people know all exists, and it may at times be preferable to a million individual declarations, depending on the structure of your CSS. On the other hand, it may have a performance penalty, although I've yet to see any data supporting that hypothesis. For now, I'll leave it, but I want people to be aware it's a mixed bag.

Original post:

You can also simply significantly with:

.nav a {
    transition: all .2s;
}

FWIW: all is implied if not specified, so transition: .2s; will get you to the same place.

How to declare an array of objects in C#

The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0], it will be null.

Here's a great little helper method you could write for yourself:

T[] InitializeArray<T>(int length) where T : new()
{
    T[] array = new T[length];
    for (int i = 0; i < length; ++i)
    {
        array[i] = new T();
    }

    return array;
}

Then you could initialize your houses array as:

GameObject[] houses = InitializeArray<GameObject>(200);

ActionBarActivity: cannot be resolved to a type

Check if you have a android-support-v4.jar file in YOUR project's lib folder, it should be removed!

In the tutorial, when you have followed the instructions of Adding libraries WITHOUT resources before doing the coorect Adding libraries WITH resources you'll get the same error.

(Don't know why someone would do something like that *lookingawayfrommyself* ^^)

So what did fix it in my case, was removing the android-support-v4.jar from YOUR PROJECT (not the android-support-v7-appcompat project), since this caused some kind of library collision (maybe because in the meantime there was a new version of the suport library).

Just another case, when this error might shows up.

Changing CSS style from ASP.NET code

I find that code gets messy fast when C# code is used to modify CSS values. Perhaps a better approach is for your code to dynamically set the class attribute on the div tag and then store any specific CSS settings in the style sheet.

That might not work for your situation, but its a decent default position if you need to change the style on the fly in server side code.

phpinfo() - is there an easy way for seeing it?

From the CLI the best way is to use grep like:

php -i | grep libxml

Form inline inside a form horizontal in twitter bootstrap?

This uses twitter bootstrap 3.x with one css class to get labels to sit on top of the inputs. Here's a fiddle link, make sure to expand results panel wide enough to see effect.

HTML:

  <div class="row myform">
     <div class="col-md-12">
        <form name="myform" role="form" novalidate>
           <div class="form-group">
              <label class="control-label" for="fullName">Address Line</label>
              <input required type="text" name="addr" id="addr" class="form-control" placeholder="Address"/>
           </div>

           <div class="form-inline">
              <div class="form-group">
                 <label>State</label>
                 <input required type="text" name="state" id="state" class="form-control" placeholder="State"/>
              </div>

              <div class="form-group">
                 <label>ZIP</label>
                 <input required type="text" name="zip" id="zip" class="form-control" placeholder="Zip"/>
              </div>
           </div>

           <div class="form-group">
              <label class="control-label" for="country">Country</label>
              <input required type="text" name="country" id="country" class="form-control" placeholder="country"/>
           </div>
        </form>
     </div>
  </div>

CSS:

.myform input.form-control {
   display: block;  /* allows labels to sit on input when inline */
   margin-bottom: 15px; /* gives padding to bottom of inline inputs */
}

store return json value in input hidden field

You can use input.value = JSON.stringify(obj) to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)

The JSON object is available on modern browsers or you can use the json2.js library from json.org

String concatenation of two pandas columns

@DanielVelkov answer is the proper one BUT using string literals is faster:

# Daniel's
%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# String literals - python 3
%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Using CSS for a fade-in effect on page load

Method 1:

If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.

CSS

#test p {
    margin-top: 25px;
    font-size: 21px;
    text-align: center;

    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 2s; /* Firefox < 16 */
        -ms-animation: fadein 2s; /* Internet Explorer */
         -o-animation: fadein 2s; /* Opera < 12.1 */
            animation: fadein 2s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation


Method 2:

Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:

jQuery

$("#test p").addClass("load");?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;

    -webkit-transition: opacity 2s ease-in;
       -moz-transition: opacity 2s ease-in;
        -ms-transition: opacity 2s ease-in;
         -o-transition: opacity 2s ease-in;
            transition: opacity 2s ease-in;
}

#test p.load {
    opacity: 1;
}

Plain JavaScript (not in the demo)

document.getElementById("test").children[0].className += " load";

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions


Method 3:

Or, you can use the method that .Mail uses:

jQuery

$("#test p").delay(1000).animate({ opacity: 1 }, 700);?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;
}

Demo

Browser Support

jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/

This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.

Embedding a media player in a website using HTML

You can use plenty of things.

  • If you're a standards junkie, you can use the HTML5 <audio> tag:

Here is the official W3C specification for the audio tag.

Usage:

<audio controls>
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
         type='audio/mp4'>
 <!-- The next two lines are only executed if the browser doesn't support MP4 files -->
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
         type='audio/ogg; codecs=vorbis'>
 <!-- The next line will only be executed if the browser doesn't support the <audio> tag-->
 <p>Your user agent does not support the HTML5 Audio element.</p>
</audio>

jsFiddle here.

Note: I'm not sure which are the best ones, as I have never used one (yet).


UPDATE: As mentioned in another answer's comment, you are using XHTML 1.0 Transitional. You might be able to get <audio> to work with some hack.


UPDATE 2: I just remembered another way to do play audio. This will work in XHTML!!! This is fully standards-compliant.

You use this JavaScript:

var aud = document.createElement("iframe");
aud.setAttribute('src', "http://yoursite.com/youraudio.mp4"); // replace with actual file path
aud.setAttribute('width', '1px');
aud.setAttribute('height', '1px');
aud.setAttribute('scrolling', 'no');
aud.style.border = "0px";
document.body.appendChild(aud);

This is my answer to another question.


UPDATE 3: To customise the controls, you can use something like this.

What is the memory consumption of an object in Java?

Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?

No.

How much memory is allocated for an object?

  • The overhead is 8 bytes on 32-bit, 12 bytes on 64-bit; and then rounded up to a multiple of 4 bytes (32-bit) or 8 bytes (64-bit).

How much additional space is used when adding an attribute?

  • Attributes range from 1 byte (byte) to 8 bytes (long/double), but references are either 4 bytes or 8 bytes depending not on whether it's 32bit or 64bit, but rather whether -Xmx is < 32Gb or >= 32Gb: typical 64-bit JVM's have an optimisation called "-UseCompressedOops" which compress references to 4 bytes if the heap is below 32Gb.

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Android 3.0

In activity_main.xml

Replace in this tag i.e <android.support.constraint.ConstraintLayout>

android.support.constraint.ConstraintLayout

with

RelativeLayout

Multiple Java versions running concurrently under Windows

Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)

If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.

unique combinations of values in selected columns in pandas data frame and count

I haven't done time test with this but it was fun to try. Basically convert two columns to one column of tuples. Now convert that to a dataframe, do 'value_counts()' which finds the unique elements and counts them. Fiddle with zip again and put the columns in order you want. You can probably make the steps more elegant but working with tuples seems more natural to me for this problem

b = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})

b['count'] = pd.Series(zip(*[b.A,b.B]))
df = pd.DataFrame(b['count'].value_counts().reset_index())
df['A'], df['B'] = zip(*df['index'])
df = df.drop(columns='index')[['A','B','count']]

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

.NET DateTime to SqlDateTime Conversion

Is it possible that the date could actually be outside that range? Does it come from user input? If the answer to either of these questions is yes, then you should always check - otherwise you're leaving your application prone to error.

You can format your date for inclusion in an SQL statement rather easily:

var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");

Making HTTP Requests using Chrome Developer tools

If you want to edit and reissue a request that you have captured in Chrome Developer Tools' Network tab:

  • Right-click the Name of the request
  • Select Copy > Copy as cURL
  • Paste to the command line (command includes cookies and headers)
  • Edit request as needed and run

enter image description here

Meaning of "n:m" and "1:n" in database design

m:n refers to many to many relationship where as 1:n means one to many relationship forexample employee(id,name,skillset) skillset(id,skillname,qualifications)

in this case the one employee can have many skills and ignoring other cases you can say that its a 1:N relationship

How to disassemble a binary executable in Linux to get the assembly code?

Let's say that you have:

#include <iostream>

double foo(double x)
{
  asm("# MyTag BEGIN"); // <- asm comment,
                        //    used later to locate piece of code
  double y = 2 * x + 1;

  asm("# MyTag END");

  return y;
}

int main()
{
  std::cout << foo(2);
}

To get assembly code using gcc you can do:

 g++ prog.cpp -c -S -o - -masm=intel | c++filt | grep -vE '\s+\.'

c++filt demangles symbols

grep -vE '\s+\.' removes some useless information

Now if you want to visualize the tagged part, simply use:

g++ prog.cpp -c -S -o - -masm=intel | c++filt | grep -vE '\s+\.' | grep "MyTag BEGIN" -A 20

With my computer I get:

    # MyTag BEGIN
# 0 "" 2
#NO_APP
    movsd   xmm0, QWORD PTR -24[rbp]
    movapd  xmm1, xmm0
    addsd   xmm1, xmm0
    addsd   xmm0, xmm1
    movsd   QWORD PTR -8[rbp], xmm0
#APP
# 9 "poub.cpp" 1
    # MyTag END
# 0 "" 2
#NO_APP
    movsd   xmm0, QWORD PTR -8[rbp]
    pop rbp
    ret
.LFE1814:
main:
.LFB1815:
    push    rbp
    mov rbp, rsp

A more friendly approach is to use: Compiler Explorer

Adding header to all request with Retrofit 2

In kotlin adding interceptor looks that way:

.addInterceptor{ it.proceed(it.request().newBuilder().addHeader("Cache-Control", "no-store").build())}

wget can't download - 404 error

I had the same problem. Solved using single quotes like this:

$ wget 'http://www.icerts.com/images/logo.jpg'

wget version in use:

$ wget --version
GNU Wget 1.11.4 Red Hat modified

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

USB Debugging option greyed out

I had an LG Android phone, and could not get USB to work with Windows, even after trying the following:

  1. Settings > About phone > Software info
  2. Tap 'Build number' 7x, and Activate Developer mode
  3. Settings > Developer options > USB debugging [ON]
  4. Settings > Developer options > Select USB Configuration > MTP
  5. Plug into Windows PC with USB cable.

It DOES show the phone as charging via USB (so the plug must be OK), but it does not show up under 'This PC' in Windows File Explorer as a Device/Drive.. grrr.

Turns out that not all USB cables are the same — some USB cable manufacturers only make their cable with 2wires instead of 4wires, so that they will charge, but not pass data through the cable — so if software solutions do not appear to be working, try changing the USB cable (!).

im writing this here so that maybe someone else doesnt have to waste half an hour figuring out that some USB cable manufacturer doesnt include all 4 wires in their USB cables... grrr.

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

Which browsers support <script async="async" />?

Just had a look at the DOM (document.scripts[1].attributes) of this page that uses google analytics. I can tell you that google is using async="".

[type="text/javascript", async="", src="http://www.google-analytics.com/ga.js"]

Where does git config --global get written to?

Uninstall Msysgit and install Cygwin + Git. Then global '.gitconfig' will be here: C:\cygwin(64)\home\[userName]\.gitconfig .

Now you don't have to worry about an environment variable which may be used by other programs. For example, my environment variable pointed me to a mapped drive in my work windows domain environment. I dont want my global .gitconfig sitting on my "home" mapped drive. I also don't know what might happen to other applications that might rely on that windows environment variable. Operations division might need that environment variable set to the mapped drive for a reason.

Also you don't have to worry about Mysysgit overwriting your 'profile' configuration settings if you specify a specific path to global '.gitconfig', using this method.

In general, save yourself and use cygwin bash shell in windows and be happier

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

How to add the JDBC mysql driver to an Eclipse project?

You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.

After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.

How do I pick randomly from an array?

Just use Array#sample:

[:foo, :bar].sample # => :foo, or :bar :-)

It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require "backports/1.9.1/array/sample".

Note that in Ruby 1.8.7 it exists under the unfortunate name choice; it was renamed in later version so you shouldn't use that.

Although not useful in this case, sample accepts a number argument in case you want a number of distinct samples.

Deleting array elements in JavaScript - delete vs splice

If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.

You can do it by building a new array. e.g

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

But I don't think you can modify the key values in the original array, which would be more efficient - it looks like you might have to create a new array.

Note that you don't need to check for the "undefined" entries as they don't actually exist and the for loop doesn't return them. It's an artifact of the array printing that displays them as undefined. They don't appear to exist in memory.

It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?


Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},

How to include view/partial specific styling in AngularJS

'use strict'; angular.module('app') .run( [ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $urlRouterProvider
                .otherwise('/app/dashboard');
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: 'views/layout.html'
                })
                .state('app.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard.html',
                    ncyBreadcrumb: {
                        label: 'Dashboard',
                        description: ''
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                .state('ram', {
                    abstract: true,
                    url: '/ram',
                    templateUrl: 'views/layout-ram.html'
                })
                .state('ram.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard-ram.html',
                    ncyBreadcrumb: {
                        label: 'test'
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                 );

How do you convert CString and std::string std::wstring to each other?

You can cast CString freely to const char* and then assign it to an std::string like this:

CString cstring("MyCString");
std::string str = (const char*)cstring;

Peak detection in a 2D array

a rough outline...

you'd probably want to use a connected components algorithm to isolate each paw region. wiki has a decent description of this (with some code) here: http://en.wikipedia.org/wiki/Connected_Component_Labeling

you'll have to make a decision about whether to use 4 or 8 connectedness. personally, for most problems i prefer 6-connectedness. anyway, once you've separated out each "paw print" as a connected region, it should be easy enough to iterate through the region and find the maxima. once you've found the maxima, you could iteratively enlarge the region until you reach a predetermined threshold in order to identify it as a given "toe".

one subtle problem here is that as soon as you start using computer vision techniques to identify something as a right/left/front/rear paw and you start looking at individual toes, you have to start taking rotations, skews, and translations into account. this is accomplished through the analysis of so-called "moments". there are a few different moments to consider in vision applications:

central moments: translation invariant normalized moments: scaling and translation invariant hu moments: translation, scale, and rotation invariant

more information about moments can be found by searching "image moments" on wiki.

Change Input to Upper Case

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

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

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

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

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

How to properly exit a C# application?

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}

Print second last column/field in awk

First decrements the value and then print it -

awk ' { print $(--NF)}' file

OR

rev file|cut -d ' ' -f2|rev

AngularJs: How to check for changes in file input fields?

I recommend to create a directive

<input type="file" custom-on-change handler="functionToBeCalled(params)">

app.directive('customOnChange', [function() {
        'use strict';

        return {
            restrict: "A",

            scope: {
                handler: '&'
            },
            link: function(scope, element){

                element.change(function(event){
                    scope.$apply(function(){
                        var params = {event: event, el: element};
                        scope.handler({params: params});
                    });
                });
            }

        };
    }]);

this directive can be used many times, it uses its own scope and doesn't depend on parent scope. You can also give some params to handler function. Handler function will be called with scope object, that was active when you changed the input. $apply updates your model each time the change event is called

Pan & Zoom Image

This will zoom in and out as well as pan but keep the image within the bounds of the container. Written as a control so add the style to the App.xaml directly or through the Themes/Viewport.xaml.

For readability I've also uploaded this on gist and github

I've also packaged this up on nuget

PM > Install-Package Han.Wpf.ViewportControl

./Controls/Viewport.cs:

public class Viewport : ContentControl
{
    private bool _capture;
    private FrameworkElement _content;
    private Matrix _matrix;
    private Point _origin;

    public static readonly DependencyProperty MaxZoomProperty =
        DependencyProperty.Register(
            nameof(MaxZoom),
            typeof(double),
            typeof(Viewport),
            new PropertyMetadata(0d));

    public static readonly DependencyProperty MinZoomProperty =
        DependencyProperty.Register(
            nameof(MinZoom),
            typeof(double),
            typeof(Viewport),
            new PropertyMetadata(0d));

    public static readonly DependencyProperty ZoomSpeedProperty =
        DependencyProperty.Register(
            nameof(ZoomSpeed),
            typeof(float),
            typeof(Viewport),
            new PropertyMetadata(0f));

    public static readonly DependencyProperty ZoomXProperty =
        DependencyProperty.Register(
            nameof(ZoomX),
            typeof(double),
            typeof(Viewport),
            new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public static readonly DependencyProperty ZoomYProperty =
        DependencyProperty.Register(
            nameof(ZoomY),
            typeof(double),
            typeof(Viewport),
            new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public static readonly DependencyProperty OffsetXProperty =
        DependencyProperty.Register(
            nameof(OffsetX),
            typeof(double),
            typeof(Viewport),
            new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public static readonly DependencyProperty OffsetYProperty =
        DependencyProperty.Register(
            nameof(OffsetY),
            typeof(double),
            typeof(Viewport),
            new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public static readonly DependencyProperty BoundsProperty =
        DependencyProperty.Register(
            nameof(Bounds),
            typeof(Rect),
            typeof(Viewport),
            new FrameworkPropertyMetadata(default(Rect), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public Rect Bounds
    {
        get => (Rect) GetValue(BoundsProperty);
        set => SetValue(BoundsProperty, value);
    }

    public double MaxZoom
    {
        get => (double) GetValue(MaxZoomProperty);
        set => SetValue(MaxZoomProperty, value);
    }

    public double MinZoom
    {
        get => (double) GetValue(MinZoomProperty);
        set => SetValue(MinZoomProperty, value);
    }

    public double OffsetX
    {
        get => (double) GetValue(OffsetXProperty);
        set => SetValue(OffsetXProperty, value);
    }

    public double OffsetY
    {
        get => (double) GetValue(OffsetYProperty);
        set => SetValue(OffsetYProperty, value);
    }

    public float ZoomSpeed
    {
        get => (float) GetValue(ZoomSpeedProperty);
        set => SetValue(ZoomSpeedProperty, value);
    }

    public double ZoomX
    {
        get => (double) GetValue(ZoomXProperty);
        set => SetValue(ZoomXProperty, value);
    }

    public double ZoomY
    {
        get => (double) GetValue(ZoomYProperty);
        set => SetValue(ZoomYProperty, value);
    }

    public Viewport()
    {
        DefaultStyleKey = typeof(Viewport);

        Loaded += OnLoaded;
        Unloaded += OnUnloaded;
    }

    private void Arrange(Size desired, Size render)
    {
        _matrix = Matrix.Identity;

        var zx = desired.Width / render.Width;
        var zy = desired.Height / render.Height;
        var cx = render.Width < desired.Width ? render.Width / 2.0 : 0.0;
        var cy = render.Height < desired.Height ? render.Height / 2.0 : 0.0;

        var zoom = Math.Min(zx, zy);

        if (render.Width > desired.Width &&
            render.Height > desired.Height)
        {
            cx = (desired.Width - (render.Width * zoom)) / 2.0;
            cy = (desired.Height - (render.Height * zoom)) / 2.0;

            _matrix = new Matrix(zoom, 0d, 0d, zoom, cx, cy);
        }
        else
        {
            _matrix.ScaleAt(zoom, zoom, cx, cy);
        }
    }

    private void Attach(FrameworkElement content)
    {
        content.MouseMove += OnMouseMove;
        content.MouseLeave += OnMouseLeave;
        content.MouseWheel += OnMouseWheel;
        content.MouseLeftButtonDown += OnMouseLeftButtonDown;
        content.MouseLeftButtonUp += OnMouseLeftButtonUp;
        content.SizeChanged += OnSizeChanged;
        content.MouseRightButtonDown += OnMouseRightButtonDown;
    }

    private void ChangeContent(FrameworkElement content)
    {
        if (content != null && !Equals(content, _content))
        {
            if (_content != null)
            {
                Detatch();
            }

            Attach(content);
            _content = content;
        }
    }

    private double Constrain(double value, double min, double max)
    {
        if (min > max)
        {
            min = max;
        }

        if (value <= min)
        {
            return min;
        }

        if (value >= max)
        {
            return max;
        }

        return value;
    }

    private void Constrain()
    {
        var x = Constrain(_matrix.OffsetX, _content.ActualWidth - _content.ActualWidth * _matrix.M11, 0);
        var y = Constrain(_matrix.OffsetY, _content.ActualHeight - _content.ActualHeight * _matrix.M22, 0);

        _matrix = new Matrix(_matrix.M11, 0d, 0d, _matrix.M22, x, y);
    }

    private void Detatch()
    {
        _content.MouseMove -= OnMouseMove;
        _content.MouseLeave -= OnMouseLeave;
        _content.MouseWheel -= OnMouseWheel;
        _content.MouseLeftButtonDown -= OnMouseLeftButtonDown;
        _content.MouseLeftButtonUp -= OnMouseLeftButtonUp;
        _content.SizeChanged -= OnSizeChanged;
        _content.MouseRightButtonDown -= OnMouseRightButtonDown;
    }

    private void Invalidate()
    {
        if (_content != null)
        {
            Constrain();

            _content.RenderTransformOrigin = new Point(0, 0);
            _content.RenderTransform = new MatrixTransform(_matrix);
            _content.InvalidateVisual();

            ZoomX = _matrix.M11;
            ZoomY = _matrix.M22;

            OffsetX = _matrix.OffsetX;
            OffsetY = _matrix.OffsetY;

            var rect = new Rect
            {
                X = OffsetX * -1,
                Y = OffsetY * -1,
                Width = ActualWidth,
                Height = ActualHeight
            };

            Bounds = rect;
        }
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        _matrix = Matrix.Identity;
    }

    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);

        if (Content is FrameworkElement element)
        {
            ChangeContent(element);
        }
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        if (Content is FrameworkElement element)
        {
            ChangeContent(element);
        }

        SizeChanged += OnSizeChanged;
        Loaded -= OnLoaded;
    }

    private void OnMouseLeave(object sender, MouseEventArgs e)
    {
        if (_capture)
        {
            Released();
        }
    }

    private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (IsEnabled && !_capture)
        {
            Pressed(e.GetPosition(this));
        }
    }

    private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (IsEnabled && _capture)
        {
            Released();
        }
    }

    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        if (IsEnabled && _capture)
        {
            var position = e.GetPosition(this);

            var point = new Point
            {
                X = position.X - _origin.X,
                Y = position.Y - _origin.Y
            };

            var delta = point;
            _origin = position;

            _matrix.Translate(delta.X, delta.Y);

            Invalidate();
        }
    }

    private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (IsEnabled)
        {
            Reset();
        }
    }

    private void OnMouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (IsEnabled)
        {
            var scale = e.Delta > 0 ? ZoomSpeed : 1 / ZoomSpeed;
            var position = e.GetPosition(_content);

            var x = Constrain(scale, MinZoom / _matrix.M11, MaxZoom / _matrix.M11);
            var y = Constrain(scale, MinZoom / _matrix.M22, MaxZoom / _matrix.M22);

            _matrix.ScaleAtPrepend(x, y, position.X, position.Y);

            ZoomX = _matrix.M11;
            ZoomY = _matrix.M22;

            Invalidate();
        }
    }

    private void OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        if (_content?.IsMeasureValid ?? false)
        {
            Arrange(_content.DesiredSize, _content.RenderSize);

            Invalidate();
        }
    }

    private void OnUnloaded(object sender, RoutedEventArgs e)
    {
        Detatch();

        SizeChanged -= OnSizeChanged;
        Unloaded -= OnUnloaded;
    }

    private void Pressed(Point position)
    {
        if (IsEnabled)
        {
            _content.Cursor = Cursors.Hand;
            _origin = position;
            _capture = true;
        }
    }

    private void Released()
    {
        if (IsEnabled)
        {
            _content.Cursor = null;
            _capture = false;
        }
    }

    private void Reset()
    {
        _matrix = Matrix.Identity;

        if (_content != null)
        {
            Arrange(_content.DesiredSize, _content.RenderSize);
        }

        Invalidate();
    }
}

./Themes/Viewport.xaml:

<ResourceDictionary ... >

    <Style TargetType="{x:Type controls:Viewport}"
           BasedOn="{StaticResource {x:Type ContentControl}}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:Viewport}">
                    <Border BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}">
                        <Grid ClipToBounds="True"
                              Width="{TemplateBinding Width}"
                              Height="{TemplateBinding Height}">
                            <Grid x:Name="PART_Container">
                                <ContentPresenter x:Name="PART_Presenter" />
                            </Grid>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

./App.xaml

<Application ... >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <ResourceDictionary Source="./Themes/Viewport.xaml"/>

            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Usage:

<viewers:Viewport>
    <Image Source="{Binding}"/>
</viewers:Viewport>

Any issues, give me a shout.

Happy coding :)

AngularJS: How to make angular load script inside ng-include?

I tried neemzy's approach, but it didn't work for me using 1.2.0-rc.3. The script tag would be inserted into the DOM, but the javascript path would not be loaded. I suspect it was because the javascript i was trying to load was from a different domain/protocol. So I took a different approach, and this is what I came up with, using google maps as an example: (Gist)

angular.module('testApp', []).
    directive('lazyLoad', ['$window', '$q', function ($window, $q) {
        function load_script() {
            var s = document.createElement('script'); // use global document since Angular's $document is weak
            s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
            document.body.appendChild(s);
        }
        function lazyLoadApi(key) {
            var deferred = $q.defer();
            $window.initialize = function () {
                deferred.resolve();
            };
            // thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
            if ($window.attachEvent) {  
                $window.attachEvent('onload', load_script); 
            } else {
                $window.addEventListener('load', load_script, false);
            }
            return deferred.promise;
        }
        return {
            restrict: 'E',
            link: function (scope, element, attrs) { // function content is optional
            // in this example, it shows how and when the promises are resolved
                if ($window.google && $window.google.maps) {
                    console.log('gmaps already loaded');
                } else {
                    lazyLoadApi().then(function () {
                        console.log('promise resolved');
                        if ($window.google && $window.google.maps) {
                            console.log('gmaps loaded');
                        } else {
                            console.log('gmaps not loaded');
                        }
                    }, function () {
                        console.log('promise rejected');
                    });
                }
            }
        };
    }]);

I hope it's helpful for someone.

How to completely uninstall Android Studio from windows(v10)?

Uninstall your android studio in control panel and remove all data in your file manager about android studio.

Where to get "UTF-8" string literal in Java?

This constant is available (among others as: UTF-16, US-ASCII, etc.) in the class org.apache.commons.codec.CharEncoding as well.

How to block until an event is fired in c#

You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

ManualResetEvent oSignalEvent = new ManualResetEvent(false);

void SecondThread(){
    //DoStuff
    oSignalEvent.Set();
}

void Main(){
    //DoStuff
    //Call second thread
    System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
    oSecondThread.Start();

    oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
    oSignalEvent.Reset();
    //Do more stuff
}

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

You can use Delorean to travel in space and time!

import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch

http://delorean.readthedocs.org/en/latest/quickstart.html  

"call to undefined function" error when calling class method

you need to call the function like this

$this->assign()

instead of just assign()

Log all queries in mysql

Enable the log for table

mysql> SET GLOBAL general_log = 'ON';
mysql> SET global log_output = 'table';

View log by select query

select * from mysql.general_log

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

Driver executable must be set by the webdriver.ie.driver system property

The error message says

"The path to the driver executable must be set by the webdriver.ie.driver system property;"

You are setting the path for the Chrome Driver with "webdriver.chrome.driver" property. You are not setting the file location when for InternetExplorerDriver, to do that you must set "webdriver.ie.driver" property.

You can set these properties in your shell, via maven, or your IDE with the -DpropertyName=Value

-Dwebdriver.ie.driver="C:/.../IEDriverServer.exe" 

You need to use quotes because of spaces or slashes in your path on windows machines, or alternatively reverse the slashes other wise they are the string string escape prefix.

You could also use

System.setProperty("webdriver.ie.driver","C:/.../IEDriverServer.exe"); 

inside your code.

Changing file extension in Python

Starting from Python 3.4 there's pathlib built-in library. So the code could be something like:

from pathlib import Path

filename = "mysequence.fasta"
new_filename = Path(filename).stem + ".aln"

https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.stem

I love pathlib :)

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

List of remotes for a Git repository?

The answers so far tell you how to find existing branches:

git branch -r

Or repositories for the same project [see note below]:

git remote -v

There is another case. You might want to know about other project repositories hosted on the same server.

To discover that information, I use SSH or PuTTY to log into to host and ls to find the directories containing the other repositories. For example, if I cloned a repository by typing:

git clone ssh://git.mycompany.com/git/ABCProject

and want to know what else is available, I log into git.mycompany.com via SSH or PuTTY and type:

ls /git

assuming ls says:

 ABCProject DEFProject

I can use the command

 git clone ssh://git.mycompany.com/git/DEFProject

to gain access to the other project.

NOTE: Usually git remote simply tells me about origin -- the repository from which I cloned the project. git remote would be handy if you were collaborating with two or more people working on the same project and accessing each other's repositories directly rather than passing everything through origin.

Create Word Document using PHP in Linux

Following on Ivan Krechetov's answer, here is a function that does mail merge (actually just simple text replace) for docx and odt, without the need for an extra library.

function mailMerge($templateFile, $newFile, $row)
{
  if (!copy($templateFile, $newFile))  // make a duplicate so we dont overwrite the template
    return false; // could not duplicate template
  $zip = new ZipArchive();
  if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
    return false; // probably not a docx file
  $file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';
  $data = $zip->getFromName($file);
  foreach ($row as $key => $value)
    $data = str_replace($key, $value, $data);
  $zip->deleteName($file);
  $zip->addFromString($file, $data);
  $zip->close();
  return true;
}

This will replace [Person Name] with Mina and [Person Last Name] with Mooo:

$replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo');
$newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');
$templateName = 'personinfo.docx';
if (mailMerge($templateName, $newFile, $replacements))
{
  header('Content-type: application/msword');
  header('Content-Disposition: attachment; filename=' . $templateName);
  header('Accept-Ranges: bytes');
  header('Content-Length: '. filesize($file));
  readfile($newFile);
  unlink($newFile);
}

Beware that this function can corrupt the document if the string to replace is too general. Try to use verbose replacement strings like [Person Name].

PostgreSQL : cast string to date DD/MM/YYYY

A DATE column does not have a format. You cannot specify a format for it.

You can use DateStyle to control how PostgreSQL emits dates, but it's global and a bit limited.

Instead, you should use to_char to format the date when you query it, or format it in the client application. Like:

SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;

e.g.

regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
  to_char   
------------
 01/04/2014
(1 row)

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc.

Reading a registry key in C#

You're looking for the cunningly named Registry.GetValue method.

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

Can I store images in MySQL

Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.

A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.

Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.

I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.

Get the records of last month in SQL server

I don't think the accepted solution is very index friendly I use the following lines instead

select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date <= dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));

Or simply (this is the best).

select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date < SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);

Some help

-- Get the first of last month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
-- Get the first of current month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
--Get the last of last month except the last 3milli seconds. (3miliseconds being used as SQL express otherwise round it up to the full second (SERIUSLY MS)
SELECT dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));

Pandas dataframe fillna() only some columns in place

You can select your desired columns and do it by assignment:

df[['a', 'b']] = df[['a','b']].fillna(value=0)

The resulting output is as expected:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

WARNING: Can't verify CSRF token authenticity rails

For those of you that do need a non jQuery answer you can simple add the following:

xmlhttp.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));

A very simple example can be sen here:

xmlhttp.open("POST","example.html",true);
xmlhttp.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
xmlhttp.send();

How to instantiate, initialize and populate an array in TypeScript?

A simple solution could be:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

MySQL ORDER BY multiple column ASC and DESC

Ok, I THINK I understand what you want now, and let me clarify to confirm before the query. You want 1 record for each user. For each user, you want their BEST POINTS score record. Of the best points per user, you want the one with the best average time. Once you have all users "best" values, you want the final results sorted with best points first... Almost like ranking of a competition.

So now the query. If the above statement is accurate, you need to start with getting the best point/average time per person and assigning a "Rank" to that entry. This is easily done using MySQL @ variables. Then, just include a HAVING clause to only keep those records ranked 1 for each person. Finally apply the order by of best points and shortest average time.

select
      U.UserName,
      PreSortedPerUser.Point,
      PreSortedPerUser.Avg_Time,
      @UserRank := if( @lastUserID = PreSortedPerUser.User_ID, @UserRank +1, 1 ) FinalRank,
      @lastUserID := PreSortedPerUser.User_ID
   from
      ( select
              S.user_id,
              S.point,
              S.avg_time
           from
              Scores S
           order by
              S.user_id,
              S.point DESC,
              S.Avg_Time ) PreSortedPerUser
         JOIN Users U
            on PreSortedPerUser.user_ID = U.ID,
      ( select @lastUserID := 0,
               @UserRank := 0 ) sqlvars 
   having
      FinalRank = 1
   order by
      Point Desc,
      Avg_Time

Results as handled by SQLFiddle

Note, due to the inline @variables needed to get the answer, there are the two extra columns at the end of each row. These are just "left-over" and can be ignored in any actual output presentation you are trying to do... OR, you can wrap the entire thing above one more level to just get the few columns you want like

select 
      PQ.UserName,
      PQ.Point,
      PQ.Avg_Time
   from
      ( entire query above pasted here ) as PQ

How do you read CSS rule values with JavaScript?

//works in IE, not sure about other browsers...

alert(classes[x].style.cssText);

Nginx: Permission denied for nginx on Ubuntu

Make sure you are running the test as a superuser.

sudo nginx -t

Or the test wont have all the permissions needed to complete the test properly.

How do I add a simple onClick event handler to a canvas element?

Probably very late to the answer but I just read this while preparing for my 70-480 exam, and found this to work -

var elem = document.getElementById('myCanvas');
elem.onclick = function() { alert("hello world"); }

Notice the event as onclick instead of onClick.

JS Bin example.

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('http://hiscore.runescape.com/index_lite.ws?player=zezima')

and read the normal way ie

page = resp.read()

Good luck though

Set maxlength in Html Textarea

<p>
   <textarea id="msgc" onkeyup="cnt(event)" rows="1" cols="1"></textarea> 
</p> 
<p id="valmess2" style="color:red" ></p>

function cnt(event)
{ 
 document.getElementById("valmess2").innerHTML=""; // init and clear if b < max     
allowed character 

 a = document.getElementById("msgc").value; 
 b = a.length; 
 if (b > 400)
  { 
   document.getElementById("valmess2").innerHTML="the max length of 400 characters is 
reached, you typed in  " + b + "characters"; 
  } 
}

maxlength is only valid for HTML5. For HTML/XHTML you have to use JavaScript and/or PHP. With PHP you can use strlen for example.This example indicates only the max length, it's NOT blocking the input.

How to compute the sum and average of elements in an array?

Start by defining all of the variables we plan on using. You'll note that for the numbers array, I'm using the literal notation of [] as opposed to the constructor method array(). Additionally, I'm using a shorter method to set multiple variables to 0.

var numbers = [], count = sum = avg = 0;

Next I'm populating my empty numbers array with the values 0 through 11. This is to get me to your original starting point. Note how I'm pushing onto the array count++. This pushing the current value of count, and then increments it for the next time around.

while ( count < 12 )
    numbers.push( count++ );

Lastly, I'm performing a function "for each" of the numbers in the numbers array. This function will handle one number at a time, which I'm identifying as "n" within the function body.

numbers.forEach(function(n){
  sum += n; 
  avg = sum / numbers.length;
});

In the end, we can output both the sum value, and the avg value to our console in order to see the result:

// Sum: 66, Avg: 5.5
console.log( 'Sum: ' + sum + ', Avg: ' + avg );

See it in action online at http://jsbin.com/unukoj/3/edit

Why can't DateTime.Parse parse UTC date

I've put together a utility method which employs all tips shown here plus some more:

    static private readonly string[] MostCommonDateStringFormatsFromWeb = {
        "yyyy'-'MM'-'dd'T'hh:mm:ssZ",  //     momentjs aka universal sortable with 'T'     2008-04-10T06:30:00Z          this is default format employed by moment().utc().format()
        "yyyy'-'MM'-'dd'T'hh:mm:ss.fffZ", //  syncfusion                                   2008-04-10T06:30:00.000Z      retarded string format for dates that syncfusion libs churn out when invoked by ejgrid for odata filtering and so on
        "O", //                               iso8601                                      2008-04-10T06:30:00.0000000
        "s", //                               sortable                                     2008-04-10T06:30:00
        "u"  //                               universal sortable                           2008-04-10 06:30:00Z
    };

    static public bool TryParseWebDateStringExactToUTC(
        out DateTime date,
        string input,
        string[] formats = null,
        DateTimeStyles? styles = null,
        IFormatProvider formatProvider = null
    )
    {
        formats = formats ?? MostCommonDateStringFormatsFromWeb;
        return TryParseDateStringExactToUTC(out date, input, formats, styles, formatProvider);
    }

    static public bool TryParseDateStringExactToUTC(
        out DateTime date,
        string input,
        string[] formats = null,
        DateTimeStyles? styles = null,
        IFormatProvider formatProvider = null
    )
    {
        styles = styles ?? DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal; //0 utc
        formatProvider = formatProvider ?? CultureInfo.InvariantCulture;

        var verdict = DateTime.TryParseExact(input, result: out date, style: styles.Value, formats: formats, provider: formatProvider);
        if (verdict && date.Kind == DateTimeKind.Local) //1
        {
            date = date.ToUniversalTime();
        }

        return verdict;

        //0 employing adjusttouniversal is vital in order for the resulting date to be in utc when the 'Z' flag is employed at the end of the input string
        //  like for instance in   2008-04-10T06:30.000Z
        //1 local should never happen with the default settings but it can happen when settings get overriden   we want to forcibly return utc though
    }

Notice the use of '-' and 'T' (single-quoted). This is done as a matter of best practice since regional settings interfere with the interpretation of chars such as '-' causing it to be interpreted as '/' or '.' or whatever your regional settings denote as date-components-separator. I have also included a second utility method which show-cases how to parse most commonly seen date-string formats fed to rest-api backends from web clients. Enjoy.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

You can replace IList<DzieckoAndOpiekun> resultV with var resultV.

Swift programmatically navigate to another view controller/scene

Swift 5

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller you will be presenting like this:

newViewController.modalPresentationStyle = .fullScreen

This is the same for both programmatically created and storyboard created controllers.

Swift 3

With a programmatically created Controller

If you want to navigate to Controller created Programmatically, then do this:

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

With a StoryBoard created Controller

If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

how to concatenate two dictionaries to create a new one in Python?

  1. Slowest and doesn't work in Python3: concatenate the items and call dict on the resulting list:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1.items() + d2.items() + d3.items())'
    
    100000 loops, best of 3: 4.93 usec per loop
    
  2. Fastest: exploit the dict constructor to the hilt, then one update:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1, **d2); d4.update(d3)'
    
    1000000 loops, best of 3: 1.88 usec per loop
    
  3. Middling: a loop of update calls on an initially-empty dict:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.67 usec per loop
    
  4. Or, equivalently, one copy-ctor and two updates:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.65 usec per loop
    

I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).

Streaming video from Android camera to server

Here is complete article about streaming android camera video to a webpage.

Android Streaming Live Camera Video to Web Page

  1. Used libstreaming on android app
  2. On server side Wowza Media Engine is used to decode the video stream
  3. Finally jWplayer is used to play the video on a webpage.

How do I add items to an array in jQuery?

Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

var list = new Array();
$.getJSON("json.js", function(data) {
    $.each(data, function(i, item) {
        console.log(item.text);
        list.push(item.text);
    });
    console.log(list.length);
});

When should we use mutex and when should we use semaphore

I think the question should be the difference between mutex and binary semaphore.

Mutex = It is a ownership lock mechanism, only the thread who acquire the lock can release the lock.

binary Semaphore = It is more of a signal mechanism, any other higher priority thread if want can signal and take the lock.

HTML5 input type range show range value

For those who are still searching for a solution without a separate javascript code. There is little easy solution without writing a javascript or jquery function:

_x000D_
_x000D_
<input type="range" value="24" min="1" max="100" oninput="this.nextElementSibling.value = this.value">
<output>24</output>
_x000D_
_x000D_
_x000D_

JsFiddle Demo

If you want to show the value in text box, simply change output to input.


Update:

It is still Javascript written within your html, you can replace the bindings with below JS code:

 document.registrationForm.ageInputId.oninput = function(){
    document.registrationForm.ageOutputId.value = document.registrationForm.ageInputId.value;
 }

Either use element's Id or name, both are supported in morden browsers.

Laravel Migration Change to Make a Column Nullable

I assume that you're trying to edit a column that you have already added data on, so dropping column and adding again as a nullable column is not possible without losing data. We'll alter the existing column.

However, Laravel's schema builder does not support modifying columns other than renaming the column. So you will need to run raw queries to do them, like this:

function up()
{
    DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}

And to make sure you can still rollback your migration, we'll do the down() as well.

function down()
{
    DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

One note is that since you are converting between nullable and not nullable, you'll need to make sure you clean up data before/after your migration. So do that in your migration script both ways:

function up()
{
    DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
    DB::statement('UPDATE `throttle` SET `user_id` = NULL WHERE `user_id` = 0;');
}

function down()
{
    DB::statement('UPDATE `throttle` SET `user_id` = 0 WHERE `user_id` IS NULL;');
    DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

Remove the newline character in a list read from a file

Here are various optimisations and applications of proper Python style to make your code a lot neater. I've put in some optional code using the csv module, which is more desirable than parsing it manually. I've also put in a bit of namedtuple goodness, but I don't use the attributes that then provides. Names of the parts of the namedtuple are inaccurate, you'll need to correct them.

import csv
from collections import namedtuple
from time import localtime, strftime

# Method one, reading the file into lists manually (less desirable)
with open('grades.dat') as files:
    grades = [[e.strip() for e in s.split(',')] for s in files]

# Method two, using csv and namedtuple
StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3')
grades = map(StudentRecord._make, csv.reader(open('grades.dat')))
# Now you could have student.id, student.lastname, etc.
# Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat')))

request = open('requests.dat', 'w')
cont = 'y'

while cont.lower() == 'y':
    answer = raw_input('Please enter the Student I.D. of whom you are looking: ')
    for student in grades:
        if answer == student[0]:
            print '%s, %s      %s      %s' % (student[1], student[2], student[0], student[3])
            time = strftime('%a, %b %d %Y %H:%M:%S', localtime())
            print time
            print 'Exams - %s, %s, %s' % student[11:14]
            print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11]
            total = sum(int(x) for x in student[4:14])
            print 'Total points earned - %d' % total
            grade = total / 5.5
            if grade >= 90:
                letter = 'an A'
            elif grade >= 80:
                letter = 'a B'
            elif grade >= 70:
                letter = 'a C'
            elif grade >= 60:
                letter = 'a D'
            else:
                letter = 'an F'

            if letter = 'an A':
                print 'Grade: %s, that is equal to %s.' % (grade, letter)
            else:
                print 'Grade: %.2f, that is equal to %s.' % (grade, letter)

            request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time))


    print
    cont = raw_input('Would you like to search again? ')

print 'Goodbye.'

Drawable image on a canvas

try this

Bitmap mBitmap = Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);

protected void onDraw(Canvas canvas) {
            canvas.drawColor(0xFFAAAAAA);
            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

        }

How to check if a value exists in an array in Ruby

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

Send parameter to Bootstrap modal window?

There is a better solution than the accepted answer, specifically using data-* attributes. Setting the id to 1 will cause you issues if any other element on the page has id=1. Instead, you can do:

<button class="btn btn-primary" data-toggle="modal" data-target="#yourModalID" data-yourparameter="whateverYouWant">Load</button>

<script>
$('#yourModalID').on('show.bs.modal', function(e) {
  var yourparameter = e.relatedTarget.dataset.yourparameter;
  // Do some stuff w/ it.
});
</script>

How can I scale the content of an iframe?

I do not think HTML has such functionality. The only thing I can imagine would do the trick is to do some server-side processing. Perhaps you could get an image snapshot of the webpage you want to serve, scale it on the server and serve it to the client. This would be a non-interactive page however. (maybe an imagemap could have the link, but still.)

Another idea would be to have a server-side component that would alter the HTML. SOrt of like the firefox 2.0 zoom feature. this of course is not perfect zooming, but is better than nothing.

Other than that, I am out of ideas.

How to enable/disable bluetooth programmatically in android

this code worked for me..

//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
} 

For this to work, you must have the following permissions:

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

Any difference between await Promise.all() and multiple await?

In case of await Promise.all([task1(), task2()]); "task1()" and "task2()" will run parallel and will wait until both promises are completed (either resolved or rejected). Whereas in case of

const result1 = await t1;
const result2 = await t2;

t2 will only run after t1 has finished execution (has been resolved or rejected). Both t1 and t2 will not run parallel.

how to count the total number of lines in a text file using python

One liner:

total_line_count = sum(1 for line in open("filename.txt"))

print(total_line_count)

Convert python datetime to epoch with strftime

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(Sorry, it wouldn't let me comment on existing answer)

creating a random number using MYSQL

Additional to this answer, create a function like

CREATE FUNCTION myrandom(
    pmin INTEGER,
    pmax INTEGER
)
RETURNS INTEGER(11)
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
  RETURN floor(pmin+RAND()*(pmax-pmin));
END; 

and call like

SELECT myrandom(100,300);

This gives you random number between 100 and 300

E: Unable to locate package npm

Your system can't find npm package because you haven't add nodejs repository to your system..

Try follow this installation step:
Add nodejs PPA repository to our system and python software properties too

sudo apt-get install curl python-software-properties 
// sudo apt-get install curl software-properties-common

curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -
sudo apt-get update

Then install npm

sudo apt-get install nodejs

Check if npm and node was installed and you're ready to use node.js

node -v
npm -v

If someone was failed to install nodejs.. Try remove the npm first, maybe the old installation was broken..

sudo apt-get remove nodejs
sudo apt-get remove npm

Check if npm or node folder still exist, delete it if you found them

which node
which npm

How to select a radio button by default?

Add this attribute:

checked="checked"

How to send a "multipart/form-data" with requests in python?

To clarify examples given above,

"You need to use the files parameter to send a multipart form POST request even when you do not need to upload any files."

files={}

won't work, unfortunately.

You will need to put some dummy values in, e.g.

files={"foo": "bar"}

I came up against this when trying to upload files to Bitbucket's REST API and had to write this abomination to avoid the dreaded "Unsupported Media Type" error:

url = "https://my-bitbucket.com/rest/api/latest/projects/FOO/repos/bar/browse/foobar.txt"
payload = {'branch': 'master', 
           'content': 'text that will appear in my file',
           'message': 'uploading directly from python'}
files = {"foo": "bar"}
response = requests.put(url, data=payload, files=files)

:O=

Can pandas automatically recognize dates?

pandas read_csv method is great for parsing dates. Complete documentation at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html

you can even have the different date parts in different columns and pass the parameter:

parse_dates : boolean, list of ints or names, list of lists, or dict
If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a
separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date
column. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

The default sensing of dates works great, but it seems to be biased towards north american Date formats. If you live elsewhere you might occasionally be caught by the results. As far as I can remember 1/6/2000 means 6 January in the USA as opposed to 1 Jun where I live. It is smart enough to swing them around if dates like 23/6/2000 are used. Probably safer to stay with YYYYMMDD variations of date though. Apologies to pandas developers,here but i have not tested it with local dates recently.

you can use the date_parser parameter to pass a function to convert your format.

date_parser : function
Function to use for converting a sequence of string columns to an array of datetime
instances. The default uses dateutil.parser.parser to do the conversion.

Sorting objects by property values

Example.

This runs on cscript.exe, on windows.

// define the Car class
(function() {
    // makeClass - By John Resig (MIT Licensed)
    // Allows either new User() or User() to be employed for construction.
    function makeClass(){
        return function(args){
            if ( this instanceof arguments.callee ) {
                if ( typeof this.init == "function" )
                    this.init.apply( this, (args && args.callee) ? args : arguments );
            } else
                return new arguments.callee( arguments );
        };
    }

    Car = makeClass();

    Car.prototype.init = function(make, model, price, topSpeed, weight) {
        this.make = make;
        this.model = model;
        this.price = price;
        this.weight = weight;
        this.topSpeed = topSpeed;
    };
})();


// create a list of cars
var autos = [
    new Car("Chevy", "Corvair", 1800, 88, 2900),
    new Car("Buick", "LeSabre", 31000, 138, 3700),
    new Car("Toyota", "Prius", 24000, 103, 3200),
    new Car("Porsche", "911", 92000, 155, 3100),
    new Car("Mercedes", "E500", 67000, 145, 3800),
    new Car("VW", "Passat", 31000, 135, 3700)
];

// a list of sorting functions
var sorters = {
    byWeight : function(a,b) {
        return (a.weight - b.weight);
    },
    bySpeed : function(a,b) {
        return (a.topSpeed - b.topSpeed);
    },
    byPrice : function(a,b) {
        return (a.price - b.price);
    },
    byModelName : function(a,b) {
        return ((a.model < b.model) ? -1 : ((a.model > b.model) ? 1 : 0));
    },
    byMake : function(a,b) {
        return ((a.make < b.make) ? -1 : ((a.make > b.make) ? 1 : 0));
    }
};

function say(s) {WScript.Echo(s);}

function show(title)
{
    say ("sorted by: "+title);
    for (var i=0; i < autos.length; i++) {
        say("  " + autos[i].model);
    }
    say(" ");
}

autos.sort(sorters.byWeight);
show("Weight");

autos.sort(sorters.byModelName);
show("Name");

autos.sort(sorters.byPrice);
show("Price");

You can also make a general sorter.

var byProperty = function(prop) {
    return function(a,b) {
        if (typeof a[prop] == "number") {
            return (a[prop] - b[prop]);
        } else {
            return ((a[prop] < b[prop]) ? -1 : ((a[prop] > b[prop]) ? 1 : 0));
        }
    };
};

autos.sort(byProperty("topSpeed"));
show("Top Speed");

Convert nested Python dict to object?

This should get your started:

class dict2obj(object):
    def __init__(self, d):
        self.__dict__['d'] = d

    def __getattr__(self, key):
        value = self.__dict__['d'][key]
        if type(value) == type({}):
            return dict2obj(value)

        return value

d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

x = dict2obj(d)
print x.a
print x.b.c
print x.d[1].foo

It doesn't work for lists, yet. You'll have to wrap the lists in a UserList and overload __getitem__ to wrap dicts.

How to display a Windows Form in full screen on top of the taskbar?

Use:

FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;

And then your form is placed over the taskbar.

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

force Maven to copy dependencies into target/lib

If you want to do this on an occasional basis (and thus don't want to change your POM), try this command-line:

mvn dependency:copy-dependencies -DoutputDirectory=${project.build.directory}/lib

If you omit the last argument, the dependences are placed in target/dependencies.

Python Pandas Replacing Header with Top Row

--another way to do this


df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0)).reset_index(drop=True)
df.columns.name = None

    Sample Number  Group Number  Sample Name  Group Name
0             1.0           1.0          s_1         g_1
1             2.0           1.0          s_2         g_1
2             3.0           1.0          s_3         g_1
3             4.0           2.0          s_4         g_2

If you like it hit up arrow. Thanks

1052: Column 'id' in field list is ambiguous

Already there are lots of answers to your question, You can do it like this also. You can give your table an alias name and use that in the select query like this:

SELECT a.id, b.id, name, section
FROM tbl_names as a 
LEFT JOIN tbl_section as b ON a.id = b.id;

Populate nested array in mongoose

I struggled with this for a whole bloody day. None of the solutions above worked. The only thing that worked in my case for an example like the following:

{
  outerProp1: {
    nestedProp1: [
      { prop1: x, prop2: y, prop3: ObjectId("....")},
      ...
    ],
    nestedProp2: [
      { prop1: x, prop2: y, prop3: ObjectId("....")},
      ...
    ]
  },
  ...
}

is to do the following: (Assuming populating after fetch - but also works when calling populate from the Model class (followed by exec))

await doc.populate({
  path: 'outerProp1.nestedProp1.prop3'
}).execPopulate()

// doc is now populated

In other words, the outermost path property has to contain the full path. No partially complete path coupled with populate properties seemed to work (and the model property doesn't seem to be necessary; makes sense since it is included in the schema). Took me a whole damn day to figure this out! Not sure why the other examples don't work.

(Using Mongoose 5.5.32)

Overloading operators in typedef structs (c++)

try this:

struct Pos{
    int x;
    int y;

    inline Pos& operator=(const Pos& other){
        x=other.x;
        y=other.y;
        return *this;
    }

    inline Pos operator+(const Pos& other) const {
        Pos res {x+other.x,y+other.y};
        return res;
    }

    const inline bool operator==(const Pos& other) const {
        return (x==other.x and y == other.y);
    }
 };  

Git pull command from different user

This command will help to pull from the repository as the different user:

git pull https://[email protected]/projectfolder/projectname.git master

It is a workaround, when you are using same machine that someone else used before you, and had saved credentials

Remove new lines from string and replace with one empty space

You can remove new line and multiple white spaces.

$pattern = '~[\r\n\s?]+~';
$name="test1 /
                     test1";
$name = preg_replace( $pattern, "$1 $2",$name);

echo $name;

Difference between $.ajax() and $.get() and $.load()

Everyone has it right. Functions .load, .get, and .post, are different ways of using the function .ajax.

Personally, I find the .ajax raw function very confusing, and prefer to use load, get, or post as I need it.

POST has the following structure:

$.post(target, post_data, function(response) { });

GET has the following:

$.get(target, post_data, function(response) { });

LOAD has the following:

$(*selector*).load(target, post_data, function(response) { });

As you can see, there are little differences between them, because its the situation that determines which one to use. Need to send the info to a file internally? Use .post (this would be most of the cases). Need to send the info in such a way that you could provide a link to the specific moment? Use .get. Both of them allow a callback where you can handle the response of the files.

An important note is that .load acts in two different manners. If you only provide the url of the target document, it will act as a get (and I say act because I tested checking for $_POST in the called PHP while using default .load behaviour and it detects $_POST, not $_GET; maybe it would be more precise to say it acts as .post without any arguments); however, as http://api.jquery.com/load/ says, once you provide an array of arguments to the function, it will POST the information to the file. Whatever the case is, .load function will directly insert the information into a DOM element, which in MANY cases is very legible, and very direct; but still provides a callback if you want to do something more with the response. Additionally, .load allows you to extract a certain block of code from a file, giving you the possibility to save a catalog, for example, in a html file, and retrieve pieces of it (items) directly into DOM elements.

Installing Python 3 on RHEL

For RHEL on Amazon Linux, using python3 I had to do :

sudo yum install python34-devel

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to access single elements in a table in R

?"[" pretty much covers the various ways of accessing elements of things.

Under usage it lists these:

x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)

x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value

The second item is sufficient for your purpose

Under Arguments it points out that with [ the arguments i and j can be numeric, character or logical

So these work:

data[1,1]
data[1,"V1"]

As does this:

data$V1[1]

and keeping in mind a data frame is a list of vectors:

data[[1]][1]
data[["V1"]][1]

will also both work.

So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)

Custom toast on Android: a simple example

STEP 1:

First create a layout for a custom toast in res/layout/custom_toast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF"
    android:orientation="horizontal"
    android:padding="5dp" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />

</LinearLayout>

STEP 2: In the Activity code, get the above custom view and attach to Toast:

// Get your custom_toast.xml ayout
LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));

// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Button is clicked!");

// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

For more help see how we Create custom Toast in Android:

http://developer.android.com/guide/topics/ui/notifiers/toasts.html

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

Get Cell Value from a DataTable in C#

If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.

var s  = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();

Hope this helps

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

I happened to run into this problem because of missing SELinux permissions. By default, SELinux only allowed apache/httpd to bind to the following ports:

80, 81, 443, 488, 8008, 8009, 8443, 9000

So binding to my httpd.conf-configured Listen 88 HTTP port and config.d/ssl.conf-configured Listen 8445 TLS/SSL port would fail with that default SELinux configuration.

To fix my problem, I had to add ports 88 and 8445 to my system's SELinux configuration:

  1. Install semanage tools: sudo yum -y install policycoreutils-python
  2. Allow port 88 for httpd: sudo semanage port -a -t http_port_t -p tcp 88
  3. Allow port 8445 for httpd: sudo semanage port -a -t http_port_t -p tcp 8445

How to get the mysql table columns data type?

First select the Database using use testDB; then execute

desc `testDB`.`images`;
-- or
SHOW FIELDS FROM images;

Output:

Get Table Columns with DataTypes

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;
}

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

SQL how to make null values come last when sorting ascending

SELECT *          
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);

See this blog post.

Plotting multiple time series on the same plot using ggplot()

If both data frames have the same column names then you should add one data frame inside ggplot() call and also name x and y values inside aes() of ggplot() call. Then add first geom_line() for the first line and add second geom_line() call with data=df2 (where df2 is your second data frame). If you need to have lines in different colors then add color= and name for eahc line inside aes() of each geom_line().

df1<-data.frame(x=1:10,y=rnorm(10))
df2<-data.frame(x=1:10,y=rnorm(10))

ggplot(df1,aes(x,y))+geom_line(aes(color="First line"))+
  geom_line(data=df2,aes(color="Second line"))+
  labs(color="Legend text")

enter image description here

slashes in url variables

You could easily replace the forward slashes / with something like an underscore _ such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.

Is it possible to set a number to NaN or infinity?

Is it possible to set a number to NaN or infinity?

Yes, in fact there are several ways. A few work without any imports, while others require import, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).

The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float:

+-------------------------------------------------------------------+
¦   result ¦ NaN          ¦ Infinity           ¦ -Infinity          ¦
¦ module   ¦              ¦                    ¦                    ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf")       ¦ -float("inf")      ¦
¦          ¦              ¦ float("infinity")  ¦ -float("infinity") ¦
¦          ¦              ¦ float("+inf")      ¦ float("-inf")      ¦
¦          ¦              ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math     ¦ math.nan     ¦ math.inf           ¦ -math.inf          ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath    ¦ cmath.nan    ¦ cmath.inf          ¦ -cmath.inf         ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy    ¦ numpy.nan    ¦ numpy.PINF         ¦ numpy.NINF         ¦
¦          ¦ numpy.NaN    ¦ numpy.inf          ¦ -numpy.inf         ¦
¦          ¦ numpy.NAN    ¦ numpy.infty        ¦ -numpy.infty       ¦
¦          ¦              ¦ numpy.Inf          ¦ -numpy.Inf         ¦
¦          ¦              ¦ numpy.Infinity     ¦ -numpy.Infinity    ¦
+-------------------------------------------------------------------+

A couple remarks to the table:

  • The float constructor is actually case-insensitive, so you can also use float("NaN") or float("InFiNiTy").
  • The cmath and numpy constants return plain Python float objects.
  • The numpy.NINF is actually the only constant I know of that doesn't require the -.
  • It is possible to create complex NaN and Infinity with complex and cmath:

    +------------------------------------------------------------------------------------------+
    ¦   result ¦ NaN+0j         ¦ 0+NaNj          ¦ Inf+0j              ¦ 0+Infj               ¦
    ¦ module   ¦                ¦                 ¦                     ¦                      ¦
    ¦----------+----------------+-----------------+---------------------+----------------------¦
    ¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf")      ¦ complex("infj")      ¦
    ¦          ¦                ¦                 ¦ complex("infinity") ¦ complex("infinityj") ¦
    +----------+----------------+-----------------+---------------------+----------------------¦
    ¦ cmath    ¦ cmath.nan ¹    ¦ cmath.nanj      ¦ cmath.inf ¹         ¦ cmath.infj           ¦
    +------------------------------------------------------------------------------------------+
    

    The options with ¹ return a plain float, not a complex.

is there any function to check whether a number is infinity or not?

Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import:

+--------------------------------------------------------------+
¦      for ¦ NaN         ¦ Infinity or    ¦ not NaN and        ¦
¦          ¦             ¦ -Infinity      ¦ not Infinity and   ¦
¦ module   ¦             ¦                ¦ not -Infinity      ¦
¦----------+-------------+----------------+--------------------¦
¦ math     ¦ math.isnan  ¦ math.isinf     ¦ math.isfinite      ¦
+----------+-------------+----------------+--------------------¦
¦ cmath    ¦ cmath.isnan ¦ cmath.isinf    ¦ cmath.isfinite     ¦
+----------+-------------+----------------+--------------------¦
¦ numpy    ¦ numpy.isnan ¦ numpy.isinf    ¦ numpy.isfinite     ¦
+--------------------------------------------------------------+

Again a couple of remarks:

  • The cmath and numpy functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.
  • The numpy functions also work for numpy arrays and everything that can be converted to one (like lists, tuple, etc.)
  • There are also functions that explicitly check for positive and negative infinity in NumPy: numpy.isposinf and numpy.isneginf.
  • Pandas offers two additional functions to check for NaN: pandas.isna and pandas.isnull (but not only NaN, it matches also None and NaT)
  • Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):

    def isnan(value):
        return value != value  # NaN is not equal to anything, not even itself
    
    infinity = float("infinity")
    
    def isinf(value):
        return abs(value) == infinity 
    
    def isfinite(value):
        return not (isnan(value) or isinf(value))
    

To summarize the expected results for these functions (assuming the input is a float):

+----------------------------------------------------------------------+
¦          input ¦ NaN   ¦ Infinity   ¦ -Infinity   ¦ something else   ¦
¦ function       ¦       ¦            ¦             ¦                  ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan          ¦ True  ¦ False      ¦ False       ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf          ¦ False ¦ True       ¦ True        ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite       ¦ False ¦ False      ¦ False       ¦ True             ¦
+----------------------------------------------------------------------+

Is it possible to set an element of an array to NaN in Python?

In a list it's no problem, you can always include NaN (or Infinity) there:

>>> [math.nan, math.inf, -math.inf, 1]  # python list
[nan, inf, -inf, 1]

However if you want to include it in an array (for example array.array or numpy.array) then the type of the array must be float or complex because otherwise it will try to downcast it to the arrays type!

>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan,  0.,  0.])

>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])

>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer

Get the element triggering an onclick event in jquery?

Try this

<input onclick="confirmSubmit(event);" type="button" value="Send" />

Along with this

function confirmSubmit(event){
            var domElement =$(event.target);
            console.log(domElement.attr('type'));
        }

I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

_x000D_
_x000D_
a {_x000D_
    background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
_x000D_
_x000D_

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

Bootstrap Collapse not Collapsing

Add jQuery and make sure only one link for jQuery cause more than one doesn't work...

How do I return JSON without using a template in Django?

Here's an example I needed for conditionally rendering json or html depending on the Request's Accept header

# myapp/views.py
from django.core import serializers                                                                                
from django.http import HttpResponse                                                                                  
from django.shortcuts import render                                                                                   
from .models import Event

def event_index(request):                                                                                             
    event_list = Event.objects.all()                                                                                  
    if request.META['HTTP_ACCEPT'] == 'application/json':                                                             
        response = serializers.serialize('json', event_list)                                                          
        return HttpResponse(response, content_type='application/json')                                                
    else:                                                                                                             
        context = {'event_list': event_list}                                                                          
        return render(request, 'polls/event_list.html', context)

you can test this with curl or httpie

$ http localhost:8000/event/
$ http localhost:8000/event/ Accept:application/json

note I opted not to use JsonReponse as that would reserialize the model unnecessarily.

How to stop creating .DS_Store on Mac?

Put following line into your ".profile" file.

Open .profile file and copy this line

find ~/ -name '.DS_Store' -delete

When you open terminal window it will automatically delete your .DS_Store file for you.