Programs & Examples On #Django context

django-context refers to the special django.template.Context class used for passing data from the view to the template

How to select all columns, except one column in pandas?

Another slight modification to @Salvador Dali enables a list of columns to exclude:

df[[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]

or

df.loc[:,[i for i in list(df.columns) if i not in [list_of_columns_to_exclude]]]

How to set a default row for a query that returns no rows?

I figured it out, and it should also work for other systems too. It's a variation of WW's answer.

select rate 
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18
union
select 0 as rate 
from d_payment_index 
where not exists( select rate 
                  from d_payment_index
                  where fy = 2007
                    and payment_year = 2008
                    and program_id = 18 )

Angular/RxJs When should I unsubscribe from `Subscription`

Since seangwright's solution (Edit 3) appears to be very useful, I also found it a pain to pack this feature into base component, and hint other project teammates to remember to call super() on ngOnDestroy to activate this feature.

This answer provide a way to set free from super call, and make "componentDestroyed$" a core of base component.

class BaseClass {
    protected componentDestroyed$: Subject<void> = new Subject<void>();
    constructor() {

        /// wrap the ngOnDestroy to be an Observable. and set free from calling super() on ngOnDestroy.
        let _$ = this.ngOnDestroy;
        this.ngOnDestroy = () => {
            this.componentDestroyed$.next();
            this.componentDestroyed$.complete();
            _$();
        }
    }

    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

And then you can use this feature freely for example:

@Component({
    selector: 'my-thing',
    templateUrl: './my-thing.component.html'
})
export class MyThingComponent extends BaseClass implements OnInit, OnDestroy {
    constructor(
        private myThingService: MyThingService,
    ) { super(); }

    ngOnInit() {
        this.myThingService.getThings()
            .takeUntil(this.componentDestroyed$)
            .subscribe(things => console.log(things));
    }

    /// optional. not a requirement to implement OnDestroy
    ngOnDestroy() {
        console.log('everything works as intended with or without super call');
    }

}

What is the difference between 'git pull' and 'git fetch'?

Briefly

git fetch is similar to pull but doesn't merge. i.e. it fetches remote updates (refs and objects) but your local stays the same (i.e. origin/master gets updated but master stays the same) .

git pull pulls down from a remote and instantly merges.

More

git clone clones a repo.

git rebase saves stuff from your current branch that isn't in the upstream branch to a temporary area. Your branch is now the same as before you started your changes. So, git pull -rebase will pull down the remote changes, rewind your local branch, replay your changes over the top of your current branch one by one until you're up-to-date.

Also, git branch -a will show you exactly what’s going on with all your branches - local and remote.

This blog post was useful:

The difference between git pull, git fetch and git clone (and git rebase) - Mike Pearce

and covers git pull, git fetch, git clone and git rebase.

UPDATE

I thought I'd update this to show how you'd actually use this in practice.

  1. Update your local repo from the remote (but don't merge):

     git fetch 
    
  2. After downloading the updates, let's see the differences:

     git diff master origin/master 
    
  3. If you're happy with those updates, then merge:

     git pull
    

Notes:

On step 2: For more on diffs between local and remotes, see: How to compare a local git branch with its remote branch?

On step 3: It's probably more accurate (e.g. on a fast changing repo) to do a git rebase origin here. See @Justin Ohms comment in another answer.

See also: http://longair.net/blog/2009/04/16/git-fetch-and-merge/

Can I dynamically add HTML within a div tag from C# on load event?

You can add a div with runat="server" to the page:

<div runat="server" id="myDiv">
</div>

and then set its InnerHtml property from the code-behind:

myDiv.InnerHtml = "your html here";

If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:

<script type="text/javascript">
    Sys.Application.add_load(MyLoad);
    function MyLoad(sender) {
        $get('<%= div.ClientID %>').innerHTML += " - text added on client";
    }
</script>

Cannot ignore .idea/workspace.xml - keeps popping up

I had to:

  • remove the file from git
  • push the commit to all remotes
  • make sure all other committers updated from remote

Commands

git rm -f .idea/workspace.xml
git remote | xargs -L1 git push --all

Other committers should run

git pull

Conditionally ignoring tests in JUnit 4

In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {
    public CTRunner(Class<?> klass) throws initializationError {
        super(klass);
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        if(shouldIgnore()) {
            return true;
        }
        return super.isIgnored(child);
    }

    private boolean shouldIgnore(class) {
        /* some custom criteria */
    }
}

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

int a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

How can I install a CPAN module into a local directory?

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

memcpy() vs memmove()

Your demo didn't expose memcpy drawbacks because of "bad" compiler, it does you a favor in Debug version. A release version, however, gives you the same output, but because of optimization.

    memcpy(str1 + 2, str1, 4);
00241013  mov         eax,dword ptr [str1 (243018h)]  // load 4 bytes from source string
    printf("New string: %s\n", str1);
00241018  push        offset str1 (243018h) 
0024101D  push        offset string "New string: %s\n" (242104h) 
00241022  mov         dword ptr [str1+2 (24301Ah)],eax  // put 4 bytes to destination
00241027  call        esi  

The register %eax here plays as a temporary storage, which "elegantly" fixes overlap issue.

The drawback emerges when copying 6 bytes, well, at least part of it.

char str1[9] = "aabbccdd";

int main( void )
{
    printf("The string: %s\n", str1);
    memcpy(str1 + 2, str1, 6);
    printf("New string: %s\n", str1);

    strcpy_s(str1, sizeof(str1), "aabbccdd");   // reset string

    printf("The string: %s\n", str1);
    memmove(str1 + 2, str1, 6);
    printf("New string: %s\n", str1);
}

Output:

The string: aabbccdd
New string: aaaabbbb
The string: aabbccdd
New string: aaaabbcc

Looks weird, it's caused by optimization, too.

    memcpy(str1 + 2, str1, 6);
00341013  mov         eax,dword ptr [str1 (343018h)] 
00341018  mov         dword ptr [str1+2 (34301Ah)],eax // put 4 bytes to destination, earlier than the above example
0034101D  mov         cx,word ptr [str1+4 (34301Ch)]  // HA, new register! Holding a word, which is exactly the left 2 bytes (after 4 bytes loaded to %eax)
    printf("New string: %s\n", str1);
00341024  push        offset str1 (343018h) 
00341029  push        offset string "New string: %s\n" (342104h) 
0034102E  mov         word ptr [str1+6 (34301Eh)],cx  // Again, pulling the stored word back from the new register
00341035  call        esi  

This is why I always choose memmove when trying to copy 2 overlapped memory blocks.

What is the difference between "is None" and "== None"

It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.

In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.

For a specific example take a numpy array where the == comparison is implemented elementwise:

import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False

Trying to use Spring Boot REST to Read JSON String from POST

To further work with array of maps, the followings could help:

@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {

  List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
  maps.addAll(payload);

}

Function Pointers in Java

Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:

http://code.google.com/p/lambdaj/wiki/Closures

CodeIgniter Disallowed Key Characters

Step1. Search for function _clean_input_keys on /system/core/Input.php

Step2. Modify this line

exit(‘Disallowed Key Characters.’);

to

exit(‘Disallowed Key Characters.’ . $str);

Step3. Refresh page to see the characters which generate the error

Step4. If you need to add those characters into the exception list, just add to this line

if ( ! preg_match(“/^[a-z0-9:_/-]+$|/i”, $str))

I add | (pipe) character on the example above

Calling an API from SQL Server stored procedure

Simple SQL triggered API call without building a code project

I know this is far from perfect or architectural purity, but I had a customer with a short term, critical need to integrate with a third party product via an immature API (no wsdl) I basically needed to call the API when a database event occurred. I was given basic call info - URL, method, data elements and Token, but no wsdl or other start to import into a code project. All recommendations and solutions seemed start with that import.

I used the ARC (Advanced Rest Client) Chrome extension and JaSON to test the interaction with the Service from a browser and refine the call. That gave me the tested, raw call structure and response and let me play with the API quickly. From there, I started trying to generate the wsdl or xsd from the json using online conversions but decided that was going to take too long to get working, so I found cURL (clouds part, music plays). cURL allowed me to send the API calls to a local manager from anywhere. I then broke a few more design rules and built a trigger that queued the DB events and a SQL stored procedure and scheduled task to pass the parameters to cURL and make the calls. I initially had the trigger calling XP_CMDShell (I know, booo) but didn't like the transactional implications or security issues, so switched to the Stored Procedure method.

In the end, DB insert matching the API call case triggers write to Queue table with parameters for API call Stored procedure run every 5 seconds runs Cursor to pull each Queue table entry, send the XP_CMDShell call to the bat file with parameters Bat file contains Curl call with parameters inserted sending output to logs. Works well.

Again, not perfect, but for a tight timeline, and a system used short term, and that can be closely monitored to react to connectivity and unforeseen issues, it worked.

Hope that helps someone struggling with limited API info get a solution going quickly.

Force HTML5 youtube video

If you're using the iframe embed api, you can put html5:1 as one of the playerVars arguments, like so:

player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: '<VIDEO ID>',
    playerVars: {
        html5: 1
    },
});

Totally works.

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

Well, it'd still be convenient (syntactically) if we could declare usual values inside the if's condition. So, here's a trick: you can make the compiler think there is an assignment of Optional.some(T) to a value like so:

    if let i = "abc".firstIndex(of: "a"),
        let i_int = .some(i.utf16Offset(in: "abc")),
        i_int < 1 {
        // Code
    }

What's NSLocalizedString equivalent in Swift?

I use next solution:

1) create extension:

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
}

2) in Localizable.strings file:

"Hi" = "??????";

3) example of use:

myLabel.text = "Hi".localized

enjoy! ;)

--upd:--

for case with comments you can use this solution:

1) Extension:

extension String {
    func localized(withComment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
    }
}

2) in .strings file:

/* with !!! */
"Hi" = "??????!!!";

3) using:

myLabel.text = "Hi".localized(withComment: "with !!!")

Best solution to protect PHP code without encryption

You need to consider your objectives:

1) Are you trying to prevent people from reading/modifying your code? If yes, you'll need an obfuscation/encryption tool. I've used Zend Guard with good success.

2) Are you trying to prevent unauthorized redistribution of your code?? A EULA/proprietary license will give you the legal power to prevent that, but won't actually stop it. An key/activation scheme will allow you to actively monitor usage, but can be removed unless you also encrypt your code. Zend Guard also has capabilities to lock a particular script to a particular customer machine and/or create time limited versions of the code if that's what you want to do.

I'm not familiar with vBulletin and the like, but they'd either need to encrypt/obfuscate or trust their users to do the right thing. In the latter case they have the protection of having a EULA which prohibits the behaviors they find undesirable, and the legal system to back up breaches of the EULA.

If you're not prepared/able to take legal action to protect your software and you don't want to encrypt/obfuscate, your options are a) Release it with a EULA so you're have a legal option if you ever need it and hope for the best, or b) consider whether an open source license might be more appropriate and just allow redistribution.

How to tell CRAN to install package dependencies automatically?

On your own system, try

install.packages("foo", dependencies=...)

with the dependencies= argument is documented as

dependencies: logical indicating to also install uninstalled packages
      which these packages depend on/link to/import/suggest (and so
      on recursively).  Not used if ‘repos = NULL’.  Can also be a
      character vector, a subset of ‘c("Depends", "Imports",
      "LinkingTo", "Suggests", "Enhances")’.

      Only supported if ‘lib’ is of length one (or missing), so it
      is unambiguous where to install the dependent packages.  If
      this is not the case it is ignored, with a warning.

      The default, ‘NA’, means ‘c("Depends", "Imports",
      "LinkingTo")’.

      ‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
      "Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
      ‘c("Depends", "Imports", "LinkingTo")’ for added
      dependencies: this installs all the packages needed to run
      ‘pkgs’, their examples, tests and vignettes (if the package
      author specified them correctly).

so you probably want a value TRUE.

In your package, list what is needed in Depends:, see the Writing R Extensions manual which is pretty clear on this.

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

how to sort an ArrayList in ascending order using Collections and Comparator

This might work?

Comparator mycomparator = 
    Collections.reverseOrder(Collections.reverseOrder());

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

org.apache.jasper.JasperException: Unable to compile class for JSP:

Please remove the servlet jar from web project,as any how, the application/web server already had.

How to execute an SSIS package from .NET?

You can use this Function if you have some variable in the SSIS.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

Random character generator with a range of (A..Z, 0..9) and punctuation

Using some simple command line (bash scripting):

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 30 | xargs
t315,qeqaszwz6kxv?761rf.cj/7gc

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 1 | xargs
f
  • cat /dev/urandom: get a random stream of char from the kernel
  • tr: keep only char char we want
  • head: take only the first n chars
  • xargs: just for adding a '\n' char

Define a struct inside a class in C++

declare class & nested struct probably in some header file

class C {
    // struct will be private without `public:` keyword
    struct S {
        // members will be public without `private:` keyword
        int sa;
        void func();
    };
    void func(S s);
};

if you want to separate the implementation/definition, maybe in some CPP file

void C::func(S s) {
    // implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
    // implementation here
}

if you want to inline the implementation, other answers will do fine.

Break string into list of characters in Python

In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.

charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes

for line in open(filePath):
    for char in line:
        charsFromFile.append(char) 
        #apply code on each character here

or if you want a one liner

#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]  

.

.

Edit: as agf mentions you can use itertools.chain.from_iterable

His method is better, unless you want the ability to specify which lines to grab list(itertools.chain.from_iterable(open(filename, 'rU)))

This does however require one to be familiar with itertools, and as a result looses some readablity

If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.

How do I get DOUBLE_MAX?

INT_MAX is just a definition in limits.h. You don't make it clear whether you need to store an integer or floating point value. If integer, and using a 64-bit compiler, use a LONG (LLONG for 32-bit).

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

visual c++: #include files from other projects in the same solution

Settings for compiler

In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.

To access the project configuration:

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->C/C++->General.
  3. Set the path under Additional Include Directories.

How to include

To include the header file, simply write the following in your code:

#include "filename.h"

Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.

If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:

// In project settings
Additional Include Directories    ..\..\libroot

// In code
#include "lib1/lib1.h"    // path is relative to libroot
#include "lib2/lib2.h"    // path is relative to libroot

Setting for linker

If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):

  1. Right-click on the project, and select Properties.
  2. Select Configuration Properties->Linker->Input
  3. Enter the library under Additional Dependencies.

JPA - Returning an auto generated id after persist()

Another option compatible to 4.0:

Before committing the changes, you can recover the new CayenneDataObject object(s) from the collection associated to the context, like this:

CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();

then access the ObjectId for each one in the collection, like:

ObjectId objectId = dataObject.getObjectId();

Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot(), it contains also the column name(s) associated to the PK as key(s):

objectId.getIdSnapshot().values()

How can I disable HREF if onclick is executed?

I solved a situation where I needed a template for the element that would handle alternatively a regular URL or a javascript call, where the js function needs a reference to the calling element. In javascript, "this" works as a self reference only in the context of a form element, e.g., a button. I didn't want a button, just the apperance of a regular link.

Examples:

<a onclick="http://blahblah" href="http://blahblah" target="_blank">A regular link</a>
<a onclick="javascript:myFunc($(this));return false" href="javascript:myFunc($(this));"  target="_blank">javascript with self reference</a>

The href and onClick attributes have the same values, exept I append "return false" on onClick when it's a javascript call. Having "return false" in the called function did not work.

Add column to dataframe with constant value

Summing up what the others have suggested, and adding a third way

You can:

where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.

'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).

All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).

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

>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000 
1312908481000

Or the help of the time module (and without date formatting):

>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0

Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html

Documentation:

Send Outlook Email Via Python?

This was one I tried using Win32:

import win32com.client as win32
import psutil
import os
import subprocess
import sys

# Drafting and sending email notification to senders. You can add other senders' email in the list
def send_notification():


    outlook = win32.Dispatch('outlook.application')
    olFormatHTML = 2
    olFormatPlain = 1
    olFormatRichText = 3
    olFormatUnspecified = 0
    olMailItem = 0x0

    newMail = outlook.CreateItem(olMailItem)
    newMail.Subject = sys.argv[1]
    #newMail.Subject = "check"
    newMail.BodyFormat = olFormatHTML    #or olFormatRichText or olFormatPlain
    #newMail.HTMLBody = "test"
    newMail.HTMLBody = sys.argv[2]
    newMail.To = "[email protected]"
    attachment1 = sys.argv[3]
    attachment2 = sys.argv[4]
    newMail.Attachments.Add(attachment1)
    newMail.Attachments.Add(attachment2)

    newMail.display()
    # or just use this instead of .display() if you want to send immediately
    newMail.Send()





# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
def open_outlook():
    try:
        subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
        os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
    except:
        print("Outlook didn't open successfully")     
#

# Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
    p = psutil.Process(item)
    if p.name() == "OUTLOOK.EXE":
        flag = 1
        break
    else:
        flag = 0

if (flag == 1):
    send_notification()
else:
    open_outlook()
    send_notification()

Sort a Custom Class List<T>

You can use linq:

var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()

Excel VBA code to copy a specific string to clipboard

If the place you're gonna paste have no problem with pasting a table formating (like the browser URL bar), I think the easiest way is this:

Sheets(1).Range("A1000").Value = string
Sheets(1).Range("A1000").Copy
MsgBox "Paste before closing this dialog."
Sheets(1).Range("A1000").Value = ""

When is it acceptable to call GC.Collect?

Have a look at this article by Rico Mariani. He gives two rules when to call GC.Collect (rule 1 is: "Don't"):

When to call GC.Collect()

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

How to sort findAll Doctrine's method?

$this->getDoctrine()->getRepository('MyBundle:MyTable')->findBy([], ['username' => 'ASC']);

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

Maven fails to find local artifact

As the options here didn't work for me, I'm sharing how I solved it:

My project has a parent project (with its own pom.xml) that has many children modules, one of which (A) has a dependency to another child (B). When I tried mvn package in A, it didn't work because B could not be resolved.

Executing mvn install in the parent directory did the job. After that, I could do mvn package inside of A and only then it could find B.

Simplest/cleanest way to implement a singleton in JavaScript

Module pattern: in "more readable style". You can see easily which methods are public and which ones are private

var module = (function(_name){
   /* Local Methods & Values */
   var _local = {
      name : _name,
      flags : {
        init : false
      }
   }

   function init(){
     _local.flags.init = true;
   }

   function imaprivatemethod(){
     alert("Hi, I'm a private method");
   }

   /* Public Methods & variables */

   var $r = {}; // This object will hold all public methods.

   $r.methdo1 = function(){
       console.log("method1 calls it");
   }

   $r.method2 = function(){
      imaprivatemethod(); // Calling private method
   }

   $r.init = function(){
      inti(); // Making 'init' public in case you want to init manually and not automatically
   }

   init(); // Automatically calling the init method

   return $r; // Returning all public methods

})("module");

Now you can use public methods like

module.method2(); // -> I'm calling a private method over a public method alert("Hi, I'm a private method")

http://jsfiddle.net/ncubica/xMwS9/

How do I concatenate two strings in Java?

The java 8 way:

StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);


StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);

dictionary update sequence element #0 has length 3; 2 is required

I was getting this error when I was updating the dictionary with the wrong syntax:

Try with these:

lineItem.values.update({attribute,value})

instead of

lineItem.values.update({attribute:value})

Difference between "\n" and Environment.NewLine

From the docs ...

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

How to make the checkbox unchecked by default always

One quick solution that came to mind :-

<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;">&nbsp</label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
  document.getElementById("markitem").checked = false;
</script>
<!-- Tested on Latest FF, Chrome, Opera and IE. -->

Take a full page screenshot with Firefox on the command-line

The Developer Toolbar GCLI and Shift+F2 shortcut were removed in Firefox version 60. To take a screenshot in 60 or newer:

  • press Ctrl+Shift+K to open the developer console (? Option+? Command+K on macOS)
  • type :screenshot or :screenshot --fullpage

Find out more regarding screenshots and other features


For Firefox versions < 60:

Press Shift+F2 or go to Tools > Web Developer > Developer Toolbar to open a command line. Write:

screenshot

and press Enter in order to take a screenshot.

To fully answer the question, you can even save the whole page, not only the visible part of it:

screenshot --fullpage

And to copy the screenshot to clipboard, use --clipboard option:

screenshot --clipboard --fullpage

Firefox 18 changes the way arguments are passed to commands, you have to add "--" before them.

You can find some documentation and the full list of commands here.

PS. The screenshots are saved into the downloads directory by default.

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

Difference between break and continue in PHP?

'continue' is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

'break' ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

Check out the following links:

http://www.php.net/manual/en/control-structures.break.php

http://www.php.net/manual/en/control-structures.continue.php

Hope it helps..

NameError: global name 'unicode' is not defined - in Python 3

Hope you are using Python 3 , Str are unicode by default, so please Replace Unicode function with String Str function.

if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False

Call a function on click event in Angular 2

The line in your controller code, which reads $scope.myFunc={ should be $scope.myFunc = function() { the function() part is important to indicate, it is a function!

The updated controller code would be

app.controller('myCtrl',['$scope',function($cope){
    $scope.myFunc = function() {
    console.log("function called");
  };
}]);

Where to place and how to read configuration resource files in servlet based application?

It just needs to be in the classpath (aka make sure it ends up under /WEB-INF/classes in the .war as part of the build).

How do I copy a folder from remote to local using scp?

What I always use is:

scp -r username@IP:/path/to/server/source/folder/  .

. (dot) : it means current folder. so copy from server and paste here only.

IP : can be an IP address like 125.55.41.311 or it can be host like ns1.mysite.com.

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.

Eg:

<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().

Eg:

public class FooReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();
    }   
}

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Answers didn't help me to solve my problem, I couldn't find (and browse) the assemblies although I installed them using Microsoft's msi installer. For me, the excel assembly is located under C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

For a class diagram using Oracle database, use the following steps:

File ? Data Modeler ? Import ? Data Dictionary ? select DB connection ? Next ? select database->select tabels -> Finish

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I ran into this issue while trying to install a PySpark package. I got around the issue by changing the TLS version with an environment variable:

echo 'export JAVA_TOOL_OPTIONS="-Dhttps.protocols=TLSv1.2"' >> ~/.bashrc
source ~/.bashrc

Getting cursor position in Python

Prerequisites

Install Tkinter. I've included the win32api for as a Windows-only solution.

Script

#!/usr/bin/env python

"""Get the current mouse position."""

import logging
import sys

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.DEBUG,
                    stream=sys.stdout)


def get_mouse_position():
    """
    Get the current position of the mouse.

    Returns
    -------
    dict :
        With keys 'x' and 'y'
    """
    mouse_position = None
    import sys
    if sys.platform in ['linux', 'linux2']:
        pass
    elif sys.platform == 'Windows':
        try:
            import win32api
        except ImportError:
            logging.info("win32api not installed")
            win32api = None
        if win32api is not None:
            x, y = win32api.GetCursorPos()
            mouse_position = {'x': x, 'y': y}
    elif sys.platform == 'Mac':
        pass
    else:
        try:
            import Tkinter  # Tkinter could be supported by all systems
        except ImportError:
            logging.info("Tkinter not installed")
            Tkinter = None
        if Tkinter is not None:
            p = Tkinter.Tk()
            x, y = p.winfo_pointerxy()
            mouse_position = {'x': x, 'y': y}
        print("sys.platform={platform} is unknown. Please report."
              .format(platform=sys.platform))
        print(sys.version)
    return mouse_position

print(get_mouse_position())

Is there a command for formatting HTML in the Atom editor?

Not Just HTML, Using atom-beautify - Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.

To Install the atom-beautify package :

  • Open Atom Editor.
  • Press Ctrl+Shift+P (Cmd+Shift+P on mac), this will open the atom Command Palette.
  • Search and click on Install Packages & Themes. A Install Package window comes up.
  • Search for Beautify package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify.
  • Now Restart atom and TADA! now you are ready for quick formatting.

To Format text Using atom-beautify :

  • Go to the file you want to format.
  • Hit Ctrl+Alt+B (Ctrl+Option+B on mac).
  • Your file is formatted in seconds.

How do you round a floating point number in Perl?

See perldoc/perlfaq:

Remember that int() merely truncates toward 0. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route.

 printf("%.3f",3.1415926535);
 # prints 3.142

The POSIX module (part of the standard Perl distribution) implements ceil(), floor(), and a number of other mathematical and trigonometric functions.

use POSIX;
$ceil  = ceil(3.5); # 4
$floor = floor(3.5); # 3

In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex module.

With 5.004, the Math::Trig module (part of the standard Perl distribution) > implements the trigonometric functions.

Internally it uses the Math::Complex module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2.

Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

To see why, notice how you'll still have an issue on half-way-point alternation:

for ($i = 0; $i < 1.01; $i += 0.05)
{
   printf "%.1f ",$i
}

0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0

Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

How do you log content of a JSON object in Node.js?

This will work with any object:

    var util = require("util");
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));

How to send only one UDP packet with netcat?

I did not find the -q1 option on my netcat. Instead I used the -w1 option. Below is the bash script I did to send an udp packet to any host and port:

#!/bin/bash

def_host=localhost
def_port=43211

HOST=${2:-$def_host}
PORT=${3:-$def_port}

echo -n "$1" | nc -4u -w1 $HOST $PORT

How to check if PHP array is associative or sequential?

Or you can just use this:

Arr::isAssoc($array)

which will check if array contains any non-numeric key or:

Arr:isAssoc($array, true)

to check if array is strictly sequencial (contains auto generated int keys 0 to n-1)

using this library.

How do I install a color theme for IntelliJ IDEA 7.0.x

If you just have the xml file of the color scheme you can:

Go to Preferences -> Editor -> Color and Fonts and use the Import button.

enter image description here

How to make in CSS an overlay over an image?

Putting this answer here as it is the top result in Google.

If you want a quick and simple way:

    filter: brightness(0.2);

*Not compatible with IE

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

My favorite slow sorting algorithm is the stooge sort:

void stooges(long *begin, long *end) {
   if( (end-begin) <= 1 ) return;
   if( begin[0] < end[-1] ) swap(begin, end-1);
   if( (end-begin) > 1 ) {
      int one_third = (end-begin)/3;
      stooges(begin, end-one_third);
      stooges(begin+one_third, end);
      stooges(begin, end-one_third);
   }
}

The worst case complexity is O(n^(log(3) / log(1.5))) = O(n^2.7095...).

Another slow sorting algorithm is actually named slowsort!

void slow(long *start, long *end) {
   if( (end-start) <= 1 ) return;
   long *middle = start + (end-start)/2;
   slow(start, middle);
   slow(middle, end);
   if( middle[-1] > end[-1] ) swap(middle-1, end-1);
   slow(start, end-1);
}

This one takes O(n ^ (log n)) in the best case... even slower than stoogesort.

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

Automating running command on Linux from Windows using PuTTY

Putty usually comes with the "plink" utility.
This is essentially the "ssh" command line command implemented as a windows .exe.
It pretty well documented in the putty manual under "Using the command line tool plink".

You just need to wrap a command like:

plink root@myserver /etc/backups/do-backup.sh

in a .bat script.

You can also use common shell constructs, like semicolons to execute multiple commands. e.g:

plink read@myhost ls -lrt /home/read/files;/etc/backups/do-backup.sh

transform object to array with lodash

_.toArray(obj);

Outputs as:

[
  {
    "name": "Ivan",
    "id": 12,
    "friends": [
      2,
      44,
      12
    ],
    "works": {
      "books": [],
      "films": []
    }
  },
  {
    "name": "John",
    "id": 22,
    "friends": [
      5,
      31,
      55
    ],
    "works": {
      "books": [],
      "films": []
    }
  }
]"

Use grep --exclude/--include syntax to not grep through certain files

In grep 2.5.1 you have to add this line to ~/.bashrc or ~/.bash profile

export GREP_OPTIONS="--exclude=\*.svn\*"

Difference between Constructor and ngOnInit

Constructor: The constructor method on an ES6 class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It’s out of Angular’s control when the constructor is invoked, which means that it’s not a suitable hook to let you know when Angular has finished initialising the component. JavaScript engine calls the constructor, not Angular directly. Which is why the ngOnInit (and $onInit in AngularJS) lifecycle hook was created. Bearing this in mind, there is a suitable scenario for using the constructor. This is when we want to utilise dependency injection - essentially for “wiring up” dependencies into the component.

As the constructor is initialised by the JavaScript engine, and TypeScript allows us to tell Angular what dependencies we require to be mapped against a specific property.

ngOnInit is purely there to give us a signal that Angular has finished initialising the component.

This phase includes the first pass at Change Detection against the properties that we may bind to the component itself - such as using an @Input() decorator.

Due to this, the @Input() properties are available inside ngOnInit, however are undefined inside the constructor, by design

Maximum number of threads in a .NET app?

i did a test on a 64bit system with c# console, the exception is type of out of memory, using 2949 threads.

I realize we should be using threading pool, which I do, but this answer is in response to the main question ;)

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

In Netbeans, we can use Tools->Options-> General Tab - > Under proxy settings, select Use system proxy settings.

This way, it uses the proxy settings provided in Settings -> Control Panel -> Internet Options -> Connections -> Lan Settings -> use automatic configuration scripts.

If you are using maven, make sure the proxy settings are not provided there, so that it uses Netbeans settings provided above for proxy.

Hope this helps.

Shreedevi

How do I concatenate or merge arrays in Swift?

My favorite method since Swift 2.0 is flatten

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

let c = [a, b].flatten()

This will return FlattenBidirectionalCollection so if you just want a CollectionType this will be enough and you will have lazy evaluation for free. If you need exactly the Array you can do this:

let c = Array([a, b].flatten())

How to get start and end of day in Javascript?

FYI (merged version of Tvanfosson)

it will return actual date => date when you are calling function

export const today = {
  iso: {
    start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
    now: () => new Date().toISOString(),
    end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
  },
  local: {
  start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
  now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
  end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
  }
}

// how to use

today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" * 

* it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)

What is the point of WORKDIR on Dockerfile?

Beware of using vars as the target directory name for WORKDIR - doing that appears to result in a "cannot normalize nothing" fatal error. IMO, it's also worth pointing out that WORKDIR behaves in the same way as mkdir -p <path> i.e. all elements of the path are created if they don't exist already.

UPDATE: I encountered the variable related problem (mentioned above) whilst running a multi-stage build - it now appears that using a variable is fine - if it (the variable) is "in scope" e.g. in the following, the 2nd WORKDIR reference fails ...

FROM <some image>
ENV varname varval
WORKDIR $varname

FROM <some other image>
WORKDIR $varname

whereas, it succeeds in this ...

FROM <some image>
ENV varname varval
WORKDIR $varname

FROM <some other image>
ENV varname varval
WORKDIR $varname

.oO(Maybe it's in the docs & I've missed it)

How can I specify system properties in Tomcat configuration on startup?

Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.

cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.

That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.

(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)

EDIT: Also, another possibility is to go for JNDI Resources.

Does Java have an exponential operator?

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

How do you check for permissions to write to a directory or file?

UPDATE:

Modified the code based on this answer to get rid of obsolete methods.

You can use the Security namespace to check this:

public void ExportToFile(string filename)
{
    var permissionSet = new PermissionSet(PermissionState.None);    
    var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
    permissionSet.AddPermission(writePermission);

    if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
    {
        using (FileStream fstream = new FileStream(filename, FileMode.Create))
        using (TextWriter writer = new StreamWriter(fstream))
        {
            // try catch block for write permissions 
            writer.WriteLine("sometext");


        }
    }
    else
    {
        //perform some recovery action here
    }

}

As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)

Is there a common Java utility to break a list into batches?

I came up with this one:

private static <T> List<List<T>> partition(Collection<T> members, int maxSize)
{
    List<List<T>> res = new ArrayList<>();

    List<T> internal = new ArrayList<>();

    for (T member : members)
    {
        internal.add(member);

        if (internal.size() == maxSize)
        {
            res.add(internal);
            internal = new ArrayList<>();
        }
    }
    if (internal.isEmpty() == false)
    {
        res.add(internal);
    }
    return res;
}

Disable mouse scroll wheel zoom on embedded Google Maps

Here is a simple solution. Just set the pointer-events: none CSS to the <iframe> to disable mouse scroll.

<div id="gmap-holder">
    <iframe width="100%" height="400" frameborder="0" style="border:0; pointer-events:none"
            src="https://www.google.com/maps/embed/v1/place?q=XXX&key=YYY"></iframe>
</div>

If you want the mouse scroll to be activated when the user clicks into the map, then use the following JS code. It will also disable the mouse scroll again, when the mouse moves out of the map.

$(function() {
    $('#gmap-holder').click(function(e) {
        $(this).find('iframe').css('pointer-events', 'all');
    }).mouseleave(function(e) {
        $(this).find('iframe').css('pointer-events', 'none');
    });
})

What is ToString("N0") format?

This is where the documentation is:

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9) ...

And this is where they talk about the default (2):

http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits.aspx

      // Displays a negative value with the default number of decimal digits (2).
      Int64 myInt = -1234;
      Console.WriteLine( myInt.ToString( "N", nfi ) );

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    How do I change the data type for a column in MySQL?

    If you want to alter the column details add a comment, use this

    ALTER TABLE [table_name] MODIFY [column_name] [new data type] DEFAULT [VALUE] COMMENT '[column comment]' 
    

    ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

    Here's how I fixed it:

    1. Opened the Install Cerificates.Command.The shell script got executed.
    2. Opened the Python 3.6.5 and typed in nltk.download().The download graphic window opened and all the packages got installed.

    Permissions error when connecting to EC2 via SSH on Mac OSx

    I was getting this error when I was trying to ssh into an ec2 instance on the private subnet from the bastion, to fix this issue, you've to run (ssh-add -K) as follow.
    
        Step 1: run "chmod 400 myEC2Key.pem"
        Step 2: run "ssh-add -K ./myEC2Key.pem" on your local machine
        Step 3: ssh -i myEC2Key.pem [email protected]
        Step 4: Now try to ssh to EC2 instance that is on a private subnet without specifying the key, for example, try ssh ec2-user@ipaddress.
    
        Hope this will help.
    Note: This solution is for Mac.
    

    Making macOS Installer Packages which are Developer ID ready

    FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

    pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg
    

    How to retrieve data from sqlite database in android and display it in TextView

    on button click, first open the database, fetch the data and close the data base like this

    public class cytaty extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.galeria);
    
            Button bLosuj = (Button) findViewById(R.id.button1);
            bLosuj.setOnClickListener(new View.OnClickListener() {
    
            public void onClick(View v) {
                myDatabaseHelper = new DatabaseHelper(cytaty.this);
                myDatabaseHelper.openDataBase();
    
                String text = myDatabaseHelper.getYourData(); //this is the method to query
    
                myDatabaseHelper.close(); 
                // set text to your TextView
                }
            });
        }
    }
    

    and your getYourData() in database class would be like this

    public String[] getAppCategoryDetail() {
    
        final String TABLE_NAME = "name of table";
    
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
        SQLiteDatabase db  = this.getReadableDatabase();
        Cursor cursor      = db.rawQuery(selectQuery, null);
        String[] data      = null;
    
        if (cursor.moveToFirst()) {
            do {
               // get the data into array, or class variable
            } while (cursor.moveToNext());
        }
        cursor.close();
        return data;
    }
    

    Cannot construct instance of - Jackson

    You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

      @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
        @JsonSubTypes({ 
          @Type(value = Bike.class, name = "bike"), 
          @Type(value = Auto.class, name = "auto"), 
          @Type(value = Car.class, name = "car")
        })
        public abstract class Vehicle {
            // fields, constructors, getters, setters
        }
    

    How to change collation of database, table, column?

    Quick way - export to SQL file, use search and replace to change the text you need to change. Create new database, import the data and then rename the old database and the new one to the old name.

    Is it possible to format an HTML tooltip (title attribute)?

    In bootstrap tooltip just use data-html="true"

    error: Your local changes to the following files would be overwritten by checkout

    You can force checkout your branch, if you do not want to commit your local changes.

    git checkout -f branch_name
    

    Double % formatting question for printf in Java

    Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

    System.out.printf("%s \r\n",String.valueOf(d));
    

    or

    System.out.printf("%s \r\n",Double.toString(d));
    

    This is what println do by default:

    System.out.println(d) 
    

    (and terminates the line)

    How to see the changes between two commits without commits in-between?

    I wrote a script which displays diff between two commits, works well on Ubuntu.

    https://gist.github.com/jacobabrahamb4/a60624d6274ece7a0bd2d141b53407bc

    #!/usr/bin/env python
    import sys, subprocess, os
    
    TOOLS = ['bcompare', 'meld']
    
    def getTool():
        for tool in TOOLS:
            try:
                out = subprocess.check_output(['which', tool]).strip()
                if tool in out:
                    return tool
            except subprocess.CalledProcessError:
                pass
        return None
    
    def printUsageAndExit():
        print 'Usage: python bdiff.py <project> <commit_one> <commit_two>'
        print 'Example: python bdiff.py <project> 0 1'
        print 'Example: python bdiff.py <project> fhejk7fe d78ewg9we'
        print 'Example: python bdiff.py <project> 0 d78ewg9we'
        sys.exit(0)
    
    def getCommitIds(name, first, second):
        commit1 = None
        commit2 = None
        try:
            first_index = int(first) - 1
            second_index = int(second) - 1
            if int(first) < 0 or int(second) < 0:
                print "Cannot handle negative values: "
                sys.exit(0)
            logs = subprocess.check_output(['git', '-C', name, 'log', '--oneline', '--reverse']).split('\n')
            if first_index >= 0:
                commit1 = logs[first_index].split(' ')[0]
            if second_index >= 0:
                commit2 = logs[second_index].split(' ')[0]
        except ValueError:
            if first != '0':
                commit1 = first
            if second != '0':
                commit2 = second
        return commit1, commit2
    
    def validateCommitIds(name, commit1, commit2):
        if commit1 == None and commit2 == None:
            print "Nothing to do, exit!"
            return False
        try:
            if commit1 != None:
                subprocess.check_output(['git', '-C', name, 'cat-file', '-t', commit1]).strip()
            if commit2 != None:
                subprocess.check_output(['git', '-C', name, 'cat-file', '-t', commit2]).strip()
        except subprocess.CalledProcessError:
            return False
        return True
    
    def cleanup(commit1, commit2):
            subprocess.check_output(['rm', '-rf', '/tmp/'+(commit1 if commit1 != None else '0'), '/tmp/'+(commit2 if commit2 != None else '0')])
    
    def checkoutCommit(name, commit):
        if commit != None:
            subprocess.check_output(['git', 'clone', name, '/tmp/'+commit])
            subprocess.check_output(['git', '-C', '/tmp/'+commit, 'checkout', commit])
        else:
            subprocess.check_output(['mkdir', '/tmp/0'])
    
    def compare(tool, commit1, commit2):
            subprocess.check_output([tool, '/tmp/'+(commit1 if commit1 != None else '0'), '/tmp/'+(commit2 if commit2 != None else '0')])
    
    if __name__=='__main__':
        tool = getTool()
        if tool == None:
            print "No GUI diff tools"
            sys.exit(0)
        if len(sys.argv) != 4:
            printUsageAndExit()
    
        name, first, second = None, 0, 0
        try:
            name, first, second = sys.argv[1], sys.argv[2], sys.argv[3]
        except IndexError:
            printUsageAndExit()
    
        commit1, commit2 = getCommitIds(name, first, second)
    
        if not validateCommitIds(name, commit1, commit2):
            sys.exit(0)
    
        cleanup(commit1, commit2)
        checkoutCommit(name, commit1)
        checkoutCommit(name, commit2)
    
        try:
            compare(tool, commit1, commit2)
        except KeyboardInterrupt:
            pass
        finally:
            cleanup(commit1, commit2)
        sys.exit(0)
    

    How do I create an .exe for a Java program?

    You could try exe4j. This is effectively what we use through its cousin install4j.

    Start new Activity and finish current one in Android?

    Use finish like this:

    Intent i = new Intent(Main_Menu.this, NextActivity.class);
    finish();  //Kill the activity from which you will go to next activity 
    startActivity(i);
    

    FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

    To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

    How to get all the values of input array element jquery

    You can use .map().

    Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.

    As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

    Use

    var arr = $('input[name="pname[]"]').map(function () {
        return this.value; // $(this).val()
    }).get();
    

    Mark error in form using Bootstrap

    Generally showing the error near where the error occurs is best. i.e. if someone has an error with entering their email, you highlight the email input box.

    This article has a couple good examples. http://uxdesign.smashingmagazine.com/2011/05/27/getting-started-with-defensive-web-design/

    Also twitter bootstrap has some nice styling that helps with that (scroll down to the Validation states section) http://twitter.github.com/bootstrap/base-css.html#forms

    Highlighting each input box is a bit more complicated, so the easy way would be to just put an bootstrap alert at the top with details of what the user did wrong. http://twitter.github.com/bootstrap/components.html#alerts

    How to hash some string with sha256 in Java?

    This was my approach using Kotlin:

    private fun getHashFromEmailString(email : String) : String{
        val charset = Charsets.UTF_8
        val byteArray = email.toByteArray(charset)
        val digest = MessageDigest.getInstance("SHA-256")
        val hash = digest.digest(byteArray)
    
        return hash.fold("", { str, it -> str + "%02x".format(it)})
    }
    

    How to sort a list of strings?

    Old question, but if you want to do locale-aware sorting without setting locale.LC_ALL you can do so by using the PyICU library as suggested by this answer:

    import icu # PyICU
    
    def sorted_strings(strings, locale=None):
        if locale is None:
           return sorted(strings)
        collator = icu.Collator.createInstance(icu.Locale(locale))
        return sorted(strings, key=collator.getSortKey)
    

    Then call with e.g.:

    new_list = sorted_strings(list_of_strings, "de_DE.utf8")
    

    This worked for me without installing any locales or changing other system settings.

    (This was already suggested in a comment above, but I wanted to give it more prominence, because I missed it myself at first.)

    Python SQLite: database is locked

    The database is locked by another process that is writing to it. You have to wait until the other transaction is committed. See the documentation of connect()

    What is the difference between "px", "dip", "dp" and "sp"?

    Moreover you should have clear understanding about the following concepts:

    Screen size:

    Actual physical size, measured as the screen's diagonal. For simplicity, Android groups all actual screen sizes into four generalized sizes: small, normal, large, and extra large.

    Screen density:

    The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen. For simplicity, Android groups all actual screen densities into four generalized densities: low, medium, high, and extra high.

    Orientation:

    The orientation of the screen from the user's point of view. This is either landscape or portrait, meaning that the screen's aspect ratio is either wide or tall, respectively. Be aware that not only do different devices operate in different orientations by default, but the orientation can change at runtime when the user rotates the device.

    Resolution:

    The total number of physical pixels on a screen. When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.

    Density-independent pixel (dp):

    A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

    Reference: Android developers site

    Git push error pre-receive hook declined

    You might not have developer access to the project or master branch. You need dev access to push new work up.

    New work meaning new branches and commits.

    mysql: get record count between two date-time

    for speed you can do this

    WHERE date(created_at) ='2019-10-21'
    

    Get connection status on Socket.io client

    Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

    Passing parameters on button action:@selector

    You can set tag of the button and access it from sender in action

    [btnHome addTarget:self action:@selector(btnMenuClicked:)     forControlEvents:UIControlEventTouchUpInside];
                        btnHome.userInteractionEnabled = YES;
                        btnHome.tag = 123;
    

    In the called function

    -(void)btnMenuClicked:(id)sender
    {
    [sender tag];
    
        if ([sender tag] == 123) {
            // Do Anything
        }
    }
    

    How to redirect DNS to different ports

    Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

    Bringing a subview to be in front of all other views

    What if the ad provider's view is not added to self.view but to something like [UIApplication sharedApplication].keyWindow?

    Try something like:

    [[UIApplication sharedApplication].keyWindow addSubview:yourSubview]
    

    or

    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:yourSubview]
    

    Is JavaScript's "new" keyword considered harmful?

    The rationale behind not using the new keyword, is simple:

    By not using it at all, you avoid the pitfall that comes with accidentally omitting it. The construction pattern that YUI uses, is an example of how you can avoid the new keyword altogether"

    var foo = function () {
        var pub= { };
        return pub;
    }
    var bar = foo();
    

    Alternatively you could so this:

    function foo() { }
    var bar = new foo();
    

    But by doing so you run risk of someone forgetting to use the new keyword, and the this operator being all fubar. AFAIK there is no advantage to doing this (other than you are used to it).

    At The End Of The Day: It's about being defensive. Can you use the new statement? Yes. Does it make your code more dangerous? Yes.

    If you have ever written C++, it's akin to setting pointers to NULL after you delete them.

    How can I give an imageview click effect like a button on Android?

    For defining the selector drawable choice

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="true"   
            android:drawable="@drawable/img_down" />
        <item android:state_selected="false"   
            android:drawable="@drawable/img_up" />
    </selector>
    

    I have to use android:state_pressed instead of android:state_selected

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed ="true"   
            android:drawable="@drawable/img_down" />
        <item android:state_pressed ="false"   
            android:drawable="@drawable/img_up" />
    </selector>
    

    How to delete selected text in the vi editor

    When using a terminal like PuTTY, usually mouse clicks and selections are not transmitted to the remote system. So, vi has no idea that you just selected some text. (There are exceptions to this, but in general mouse actions aren't transmitted.)

    To delete multiple lines in vi, use something like 5dd to delete 5 lines.

    If you're not using Vim, I would strongly recommend doing so. You can use visual selection, where you press V to start a visual block, move the cursor to the other end, and press d to delete (or any other editing command, such as y to copy).

    Makefiles with source files in different directories

    If the sources are spread in many folders, and it makes sense to have individual Makefiles then as suggested before, recursive make is a good approach, but for smaller projects I find it easier to list all the source files in the Makefile with their relative path to the Makefile like this:

    # common sources
    COMMON_SRC := ./main.cpp \
                  ../src1/somefile.cpp \
                  ../src1/somefile2.cpp \
                  ../src2/somefile3.cpp \
    

    I can then set VPATH this way:

    VPATH := ../src1:../src2
    

    Then I build the objects:

    COMMON_OBJS := $(patsubst %.cpp, $(ObjDir)/%$(ARCH)$(DEBUG).o, $(notdir $(COMMON_SRC)))
    

    Now the rule is simple:

    # the "common" object files
    $(ObjDir)/%$(ARCH)$(DEBUG).o : %.cpp Makefile
        @echo creating $@ ...
        $(CXX) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<
    

    And building the output is even easier:

    # This will make the cbsdk shared library
    $(BinDir)/$(OUTPUTBIN): $(COMMON_OBJS)
        @echo building output ...
        $(CXX) -o $(BinDir)/$(OUTPUTBIN) $(COMMON_OBJS) $(LFLAGS)
    

    One can even make the VPATH generation automated by:

    VPATH := $(dir $(COMMON_SRC))
    

    Or using the fact that sort removes duplicates (although it should not matter):

    VPATH := $(sort  $(dir $(COMMON_SRC)))
    

    What is the difference between application server and web server?

    IMO, it's mostly about separating concerns.

    From a purely technical point of view, you can do everything (web content + business logic) in a single web server. If you'd do that, then the information would be embedded inside requested the HTML content. What would be the impact?

    For example, imagine you have 2 different apps which renders entirely different HTML content on the browser. If you would separate the business logic into an app-server than you could provide different web-servers looking up the same data in the app-server via scripts. However, If you wouldn't separate the logic and keep it in the web-server, whenever you change your business model, you would end up changing it in every single web-server you have which would take more time, be less reliable and error-prone.

    Iterating through struct fieldnames in MATLAB

    You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.

    >> signal
    signal = 
    sin: {{1x1x25 cell}  {1x1x25 cell}}
    cos: {{1x1x25 cell}  {1x1x25 cell}}
    
    >> each(fieldnames(signal))
    ans = 
    CellIterator with properties:
    
    NumberOfIterations: 2.0000e+000
    

    Usage:

    for bridge = each(fieldnames(signal))
       signal.(bridge) = rand(10);
    end
    

    I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.

    Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

    I was facing same issue and it is resolved by removing error from resource files like style, colors files in values folder. In my case, error in style colors as below:

     <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="android:textColorPrimary">**@color/colorPrimary**</item>
        <item name="android:textColorSecondary">**@color/colorPrimaryDark**</item>
    </style>
    

    Failed to load JavaHL Library

    My Understanding - Basically, svn client comes by default on Mac os. While installing in eclipse we should match svn plugin to the mac plugin and javaHL wont be missing. There is a lengthy process to update by installing xcode and then by using homebrew or macports which you can find after googling but if you are in hurry use simply the steps below.

    1) on your mac terminal shell

    $ svn --version

    Note down the version e.g. 1.7.

    2) open the link below

    http://subclipse.tigris.org/wiki/JavaHL

    check which version of subclipse you need corresponding to it. e.g.

    Subclipse Version SVN/JavaHL Version 1.8.x 1.7.x

    3) ok, pick up url corresponding to 1.8.x from

    http://subclipse.tigris.org/servlets/ProjectProcess?pageID=p4wYuA

    and add to your eclipse => Install new Software under help

    select whatever you need, svn client or subclipse or mylyn etc and it will ask for restart of STS/eclipse thats it you are done. worked for me.

    NOTE: if you already have multiple versions installed inside your eclipse then its best to uninstall all subclipse or svn client versions from eclipse plugins and start fresh with steps listed above.

    Filter by Dates in SQL

    Well you are trying to compare Date with Nvarchar which is wrong. Should be

    Where dates between date1 And date2
    -- both date1 & date2 should be date/datetime
    

    If date1,date2 strings; server will convert them to date type before filtering.

    WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

    In my case I had to enable SchUseStrongCrypto for .Net This forces the server to make connection by using TLS 1.0, 1.1 or 1.2. Without SchUseStrongCrypto enabled the connection was trying to use SSL 3.0, which was disabled at my remote endpoint.

    Registry keys to enable use of strong crypto:

    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319]
    "SchUseStrongCrypto"=dword:00000001
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
    "SchUseStrongCrypto"=dword:00000001
    

    possibly undefined macro: AC_MSG_ERROR

    On Mac OS X el captain with brew, try:
    brew install pkgconfig

    This worked for me.

    How do I tell Python to convert integers into words

    Here's a way to do it in Python 3:

    """Given an int32 number, print it in English."""
    def int_to_en(num):
        d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',
              6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',
              11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',
              15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen',
              19 : 'nineteen', 20 : 'twenty',
              30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty',
              70 : 'seventy', 80 : 'eighty', 90 : 'ninety' }
        k = 1000
        m = k * 1000
        b = m * 1000
        t = b * 1000
    
        assert(0 <= num)
    
        if (num < 20):
            return d[num]
    
        if (num < 100):
            if num % 10 == 0: return d[num]
            else: return d[num // 10 * 10] + '-' + d[num % 10]
    
        if (num < k):
            if num % 100 == 0: return d[num // 100] + ' hundred'
            else: return d[num // 100] + ' hundred and ' + int_to_en(num % 100)
    
        if (num < m):
            if num % k == 0: return int_to_en(num // k) + ' thousand'
            else: return int_to_en(num // k) + ' thousand, ' + int_to_en(num % k)
    
        if (num < b):
            if (num % m) == 0: return int_to_en(num // m) + ' million'
            else: return int_to_en(num // m) + ' million, ' + int_to_en(num % m)
    
        if (num < t):
            if (num % b) == 0: return int_to_en(num // b) + ' billion'
            else: return int_to_en(num // b) + ' billion, ' + int_to_en(num % b)
    
        if (num % t == 0): return int_to_en(num // t) + ' trillion'
        else: return int_to_en(num // t) + ' trillion, ' + int_to_en(num % t)
    
        raise AssertionError('num is too large: %s' % str(num))
    

    And the result is:

    0 zero
    3 three
    10 ten
    11 eleven
    19 nineteen
    20 twenty
    23 twenty-three
    34 thirty-four
    56 fifty-six
    80 eighty
    97 ninety-seven
    99 ninety-nine
    100 one hundred
    101 one hundred and one
    110 one hundred and ten
    117 one hundred and seventeen
    120 one hundred and twenty
    123 one hundred and twenty-three
    172 one hundred and seventy-two
    199 one hundred and ninety-nine
    200 two hundred
    201 two hundred and one
    211 two hundred and eleven
    223 two hundred and twenty-three
    376 three hundred and seventy-six
    767 seven hundred and sixty-seven
    982 nine hundred and eighty-two
    999 nine hundred and ninety-nine
    1000 one thousand
    1001 one thousand, one
    1017 one thousand, seventeen
    1023 one thousand, twenty-three
    1088 one thousand, eighty-eight
    1100 one thousand, one hundred
    1109 one thousand, one hundred and nine
    1139 one thousand, one hundred and thirty-nine
    1239 one thousand, two hundred and thirty-nine
    1433 one thousand, four hundred and thirty-three
    2000 two thousand
    2010 two thousand, ten
    7891 seven thousand, eight hundred and ninety-one
    89321 eighty-nine thousand, three hundred and twenty-one
    999999 nine hundred and ninety-nine thousand, nine hundred and ninety-nine
    1000000 one million
    2000000 two million
    2000000000 two billion
    

    Batch script to delete files

    Consider that the files you need to delete have an extension txt and is located in the location D:\My Folder, then you could use the below code inside the bat file.

    cd "D:\My Folder"
    DEL *.txt 
    

    How to call a button click event from another method

    we have 2 form in this project. in main form change

    private void button1_Click(object sender, EventArgs e) { // work }

    to

    public void button1_Click(object sender, EventArgs e) { // work }

    and in other form, when we need above function

            private void button2_Click(object sender, EventArgs e)
        {
            main_page() obj = new main_page();
            obj.button2_Click(sender, e);
        }
    

    Are the decimal places in a CSS width respected?

    They seem to round up the values to the closest integer; but Iam seeing inconsistency in chrome,safari and firefox.

    For e.g if 33.3% converts to 420.945px

    chrome and firexfox show it as 421px. while safari shows its as 420px.

    This seems like chrome and firefox follow the floor and ceil logic while safari doesn't. This page seems to discuss the same problem

    http://ejohn.org/blog/sub-pixel-problems-in-css/

    How to position a DIV in a specific coordinates?

    Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;

    var d = document.getElementById('yourDivId');
    d.style.position = "absolute";
    d.style.left = x_pos+'px';
    d.style.top = y_pos+'px';
    

    Or do it as a function so you can attach it to an event like onmousedown

    function placeDiv(x_pos, y_pos) {
      var d = document.getElementById('yourDivId');
      d.style.position = "absolute";
      d.style.left = x_pos+'px';
      d.style.top = y_pos+'px';
    }
    

    What does the symbol \0 mean in a string-literal?

    Specifically, I want to mention one situation, by which you may confuse.

    What is the difference between "\0" and ""?

    The answer is that "\0" represents in array is {0 0} and "" is {0}.

    Because "\0" is still a string literal and it will also add "\0" at the end of it. And "" is empty but also add "\0".

    Understanding of this will help you understand "\0" deeply.

    How do I import material design library to Android Studio?

    There is a new official design library, just add this to your build.gradle: for details visit android developers page

    compile 'com.android.support:design:27.0.0'
    

    How do I set a Windows scheduled task to run in the background?

    As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


    It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

    enter image description here

    enter image description here

    enter image description here

    How can I print the contents of a hash in Perl?

    I really like to sort the keys in one liner code:

    print "$_ => $my_hash{$_}\n" for (sort keys %my_hash);
    

    How do you unit test private methods?

    Here is good article about unit testing of private methods. But I'm not sure what's better, to make you application designed specially for testing(it's like creating tests for testing only) or use reflexion for testing. Pretty sure most of us will choose second way.

    Run JavaScript in Visual Studio Code

    I faced this exact problem, when i first start to use VS Code with extension Code Runner

    The things you need to do is set the node.js path in User Settings

    You need to set the Path as you Install it in your Windows Machine.

    For mine It was \"C:\\Program Files\\nodejs\\node.exe\"

    As I have a Space in my File Directory Name

    See this Image below. I failed to run the code at first cause i made a mistake in the Path Name enter image description here

    Hope this will help you.

    And ofcourse, Your Question helped me, as i was also come here to get a help to run JS in my VS CODE

    How do I add options to a DropDownList using jQuery?

    You may want to clear your DropDown first $('#DropDownQuality').empty();

    I had my controller in MVC return a select list with only one item.

    $('#DropDownQuality').append(
            $('<option></option>').val(data[0].Value).html(data[0].Text));    
    

    How can I use numpy.correlate to do autocorrelation?

    I use talib.CORREL for autocorrelation like this, I suspect you could do the same with other packages:

    def autocorrelate(x, period):
    
        # x is a deep indicator array 
        # period of sample and slices of comparison
    
        # oldest data (period of input array) may be nan; remove it
        x = x[-np.count_nonzero(~np.isnan(x)):]
        # subtract mean to normalize indicator
        x -= np.mean(x)
        # isolate the recent sample to be autocorrelated
        sample = x[-period:]
        # create slices of indicator data
        correls = []
        for n in range((len(x)-1), period, -1):
            alpha = period + n
            slices = (x[-alpha:])[:period]
            # compare each slice to the recent sample
            correls.append(ta.CORREL(slices, sample, period)[-1])
        # fill in zeros for sample overlap period of recent correlations    
        for n in range(period,0,-1):
            correls.append(0)
        # oldest data (autocorrelation period) will be nan; remove it
        correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])      
    
        return correls
    
    # CORRELATION OF BEST FIT
    # the highest value correlation    
    max_value = np.max(correls)
    # index of the best correlation
    max_index = np.argmax(correls)
    

    Rails migration for change column

    With Rails 5

    From Rails Guides:

    If you wish for a migration to do something that Active Record doesn’t know how to reverse, you can use reversible:

    class ChangeTablenameFieldname < ActiveRecord::Migration[5.1]
      def change
        reversible do |dir|
          change_table :tablename do |t|
            dir.up   { t.change :fieldname, :date }
            dir.down { t.change :fieldname, :datetime }
          end
        end
      end
    end
    

    How to generate unique IDs for form labels in React?

    This solutions works fine for me.

    utils/newid.js:

    let lastId = 0;
    
    export default function(prefix='id') {
        lastId++;
        return `${prefix}${lastId}`;
    }
    

    And I can use it like this:

    import newId from '../utils/newid';
    
    React.createClass({
        componentWillMount() {
            this.id = newId();
        },
        render() {
            return (
                <label htmlFor={this.id}>My label</label>
                <input id={this.id} type="text"/>
            );
        }
    });
    

    But it won’t work in isomorphic apps.

    Added 17.08.2015. Instead of custom newId function you can use uniqueId from lodash.

    Updated 28.01.2016. It’s better to generate ID in componentWillMount.

    How to play .wav files with java

    A solution without java reflection DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat)

    Java reflection decrease performance. to run: java playsound absoluteFilePathTo/file.wav

    import javax.sound.sampled.*;
    import java.io.*;
    public class playsound {
    
        public static void main (String args[]) throws Exception {
            playSound (args[0]);
        }
    
        public static void playSound () throws Exception {
            AudioInputStream 
            audioStream = AudioSystem.getAudioInputStream(new File (filename));
    
            int BUFFER_SIZE = 128000;
            AudioFormat audioFormat = null;
            SourceDataLine sourceLine = null;
    
            audioFormat = audioStream.getFormat();
    
            sourceLine = AudioSystem.getSourceDataLine(audioFormat);
            sourceLine.open(audioFormat);
            sourceLine.start();
    
            int nBytesRead = 0;
            byte[] abData = new byte[BUFFER_SIZE];
            while (nBytesRead != -1) {
                try {
                    nBytesRead = 
                    audioStream.read(abData, 0, abData.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                if (nBytesRead >= 0) {
                    int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
                }
            }
    
            sourceLine.drain();
            sourceLine.close();
        }
    
    }
    

    sorting a List of Map<String, String>

    Bit out of topic
    this is a little util for watching sharedpreferences
    based on upper answers
    may be for someone this will be helpful

    @SuppressWarnings("unused")
    public void printAll() {
        Map<String, ?> prefAll = PreferenceManager
            .getDefaultSharedPreferences(context).getAll();
        if (prefAll == null) {
            return;
        }
        List<Map.Entry<String, ?>> list = new ArrayList<>();
        list.addAll(prefAll.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, ?>>() {
            public int compare(final Map.Entry<String, ?> entry1, final Map.Entry<String, ?> entry2) {
                return entry1.getKey().compareTo(entry2.getKey());
            }
        });
        Timber.i("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        Timber.i("Printing all sharedPreferences");
        for(Map.Entry<String, ?> entry : list) {
            Timber.i("%s: %s", entry.getKey(), entry.getValue());
        }
        Timber.i("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }
    

    Deploying website: 500 - Internal server error

    For IIS 8 There is a extra step to do other than changing the customErrors=Off to show the error content.

    <system.web>
       <customErrors mode="Off" />
    </system.web>
    <system.webServer>
       <httpErrors existingResponse="PassThrough" errorMode="Detailed"/>
    </system.webServer>
    

    Raul answered the question in this link Turn off IIS8 custom errors by Raul

    ViewBag, ViewData and TempData

    TempData in Asp.Net MVC is one of the very useful feature. It is used to pass data from current request to subsequent request. In other words if we want to send data from one page to another page while redirection occurs, we can use TempData, but we need to do some consideration in code to achieve this feature in MVC. Because the life of TempData is very short and lies only till the target view is fully loaded. But, we can use Keep() method to persist data in TempData.

    Read More

    Package name does not correspond to the file path - IntelliJ

    You should declare in the Project structure(Ctrl+Alt+Shift+s) in the Module section mark your folders which of them are source package(blue one) and which are test ...

    Make an existing Git branch track a remote branch?

    In a somewhat related way I was trying to add a remote tracking branch to an existing branch, but did not have access to that remote repository on the system where I wanted to add that remote tracking branch on (because I frequently export a copy of this repo via sneakernet to another system that has the access to push to that remote). I found that there was no way to force adding a remote branch on the local that hadn't been fetched yet (so local did not know that the branch existed on the remote and I would get the error: the requested upstream branch 'origin/remotebranchname' does not exist).

    In the end I managed to add the new, previously unknown remote branch (without fetching) by adding a new head file at .git/refs/remotes/origin/remotebranchname and then copying the ref (eyeballing was quickest, lame as it was ;-) from the system with access to the origin repo to the workstation (with the local repo where I was adding the remote branch on).

    Once that was done, I could then use git branch --set-upstream-to=origin/remotebranchname

    Split varchar into separate columns in Oracle

    Simple way is to convert into column

    SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))
    
    CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);
    
    CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
       RETURN split_tbl
       PIPELINED IS
       l_idx PLS_INTEGER;
       l_list VARCHAR2 (32767) := p_list;
       l_value VARCHAR2 (32767);
    BEGIN
       LOOP
          l_idx := INSTR (l_list, p_del);
    
          IF l_idx > 0 THEN
             PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
             l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
          ELSE
             PIPE ROW (l_list);
             EXIT;
          END IF;
       END LOOP;
    
       RETURN;
    END split;
    

    How to get an isoformat datetime string including the default timezone?

    You need to make your datetime objects timezone aware. from the datetime docs:

    There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

    When you have an aware datetime object, you can use isoformat() and get the output you need.

    To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

    Using pytz, this would look like:

    import datetime, pytz
    datetime.datetime.now(pytz.timezone('US/Central')).isoformat()
    

    You can also control the output format, if you use strftime with the '%z' format directive like

    datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
    

    jQuery change method on input type="file"

    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/

    $('#imageFile').on("change", function(){ uploadFile(); });
    

    C#: HttpClient with POST parameters

    As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

    The querystring (get) parameters included in your url probably will not do anything.

    Try this:

    string url = "http://myserver/method";    
    string content = "param1=1&param2=2";
    HttpClientHandler handler = new HttpClientHandler();
    HttpClient httpClient = new HttpClient(handler);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
    HttpResponseMessage response = await httpClient.SendAsync(request,content);
    

    HTH,

    bovako

    Hexadecimal to Integer in Java

    That's because the byte[] output is well, and array of bytes, you may think on it as an array of bytes representing each one an integer, but when you add them all into a single string you get something that is NOT an integer, that's why. You may either have it as an array of integers or try to create an instance of BigInteger.

    jquery, selector for class within id

    I think your asking to select only <span class = "my_class">hello</span> this element, You have do like this, If I am understand your question correctly this is the answer,

    $("#my_id [class='my_class']").addClass('test');
    

    DEMO

    Is there a good JSP editor for Eclipse?

    You could check out JBoss Tools plugin.

    What do the terms "CPU bound" and "I/O bound" mean?

    When your program is waiting for I/O (ie. a disk read/write or network read/write etc), the CPU is free to do other tasks even if your program is stopped. The speed of your program will mostly depend on how fast that IO can happen, and if you want to speed it up you will need to speed up the I/O.

    If your program is running lots of program instructions and not waiting for I/O, then it is said to be CPU bound. Speeding up the CPU will make the program run faster.

    In either case, the key to speeding up the program might not be to speed up the hardware, but to optimize the program to reduce the amount of IO or CPU it needs, or to have it do I/O while it also does CPU intensive stuff.

    Converting string to Date and DateTime

    You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:

    $ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
    

    That way you are not at the whims of a certain interpretation.

    JavaScript Extending Class

    Try this:

    Function.prototype.extends = function(parent) {
      this.prototype = Object.create(parent.prototype);
    };
    
    Monkey.extends(Monster);
    function Monkey() {
      Monster.apply(this, arguments); // call super
    }
    

    Edit: I put a quick demo here http://jsbin.com/anekew/1/edit. Note that extends is a reserved word in JS and you may get warnings when linting your code, you can simply name it inherits, that's what I usually do.

    With this helper in place and using an object props as only parameter, inheritance in JS becomes a bit simpler:

    Function.prototype.inherits = function(parent) {
      this.prototype = Object.create(parent.prototype);
    };
    
    function Monster(props) {
      this.health = props.health || 100;
    }
    
    Monster.prototype = {
      growl: function() {
        return 'Grrrrr';
      }
    };
    
    Monkey.inherits(Monster);
    function Monkey() {
      Monster.apply(this, arguments);
    }
    
    var monkey = new Monkey({ health: 200 });
    
    console.log(monkey.health); //=> 200
    console.log(monkey.growl()); //=> "Grrrr"
    

    Convert Enum to String

    In my tests, Enum.GetName was faster and by decent margin. Internally ToString calls Enum.GetName. From source for .NET 4.0, the essentials:

    public override String ToString()
    {
         return Enum.InternalFormat((RuntimeType)GetType(), GetValue());
    }
    
    private static String InternalFormat(RuntimeType eT, Object value)
    {
        if (!eT.IsDefined(typeof(System.FlagsAttribute), false))
        {
            String retval = GetName(eT, value); //<== the one
            if (retval == null)
                return value.ToString();
            else
                return retval;
        }
        else
        {
            return InternalFlagsFormat(eT, value);
        }
    }
    

    I cant say that is the reason for sure, but tests state one is faster than the other. Both the calls involve boxing (in fact they are reflection calls, you're essentially retrieving field names) and can be slow for your liking.

    Test setup: enum with 8 values, no. of iterations = 1000000

    Result: Enum.GetName => 700 ms, ToString => 2000 ms

    If speed isn't noticeable, I wouldn't care and use ToString since it offers a much cleaner call. Contrast

    Enum.GetName(typeof(Bla), value)
    

    with

    value.ToString()
    

    How to "test" NoneType in python?

    It can also be done with isinstance as per Alex Hall's answer :

    >>> NoneType = type(None)
    >>> x = None
    >>> type(x) == NoneType
    True
    >>> isinstance(x, NoneType)
    True
    

    isinstance is also intuitive but there is the complication that it requires the line

    NoneType = type(None)

    which isn't needed for types like int and float.

    HTML / CSS How to add image icon to input type="button"?

    This should do do what you want, assuming your button image is 16 by 16 pixels.

    <input type="button" value="Add a new row" class="button-add" />
    
    input.button-add {
        background-image: url(/images/buttons/add.png); /* 16px x 16px */
        background-color: transparent; /* make the button transparent */
        background-repeat: no-repeat;  /* make the background image appear only once */
        background-position: 0px 0px;  /* equivalent to 'top left' */
        border: none;           /* assuming we don't want any borders */
        cursor: pointer;        /* make the cursor like hovering over an <a> element */
        height: 16px;           /* make this the size of your image */
        padding-left: 16px;     /* make text start to the right of the image */
        vertical-align: middle; /* align the text vertically centered */
    }
    

    Example button:

    example button

    Update

    If you happen to use Less, this mixin might come in handy.

    .icon-button(@icon-url, @icon-size: 16px, @icon-inset: 10px, @border-color: #000, @background-color: transparent) {
        height: @icon-size * 2;
        padding-left: @icon-size + @icon-inset * 2;
        padding-right: @icon-inset;
        border: 1px solid @border-color;
        background: @background-color url(@icon-url) no-repeat @icon-inset center;
        cursor: pointer;
    }
    
    input.button-add {
        .icon-button("http://placehold.it/16x16", @background-color: #ff9900);
    }
    

    The above compiles into

    input.button-add {
      height: 32px;
      padding-left: 36px;
      padding-right: 10px;
      border: 1px solid #000000;
      background: #ff9900 url("http://placehold.it/16x16") no-repeat 10px center;
      cursor: pointer;
    }
    

    JSFiddle

    How to clear a chart from a canvas so that hover events cannot be triggered?

    Since destroy kind of destroys "everything", a cheap and simple solution when all you really want is to just "reset the data". Resetting your datasets to an empty array will work perfectly fine as well. So, if you have a dataset with labels, and an axis on each side:

    window.myLine2.data.labels = [];
    window.myLine2.data.datasets[0].data = [];
    window.myLine2.data.datasets[1].data = [];
    

    After this, you can simply call:

    window.myLine2.data.labels.push(x);
    window.myLine2.data.datasets[0].data.push(y);
    

    or, depending whether you're using a 2d dataset:

    window.myLine2.data.datasets[0].data.push({ x: x, y: y});
    

    It'll be a lot more lightweight than completely destroying your whole chart/dataset, and rebuilding everything.

    "No X11 DISPLAY variable" - what does it mean?

    One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.

    java.nio.file.Path for a classpath resource

    This one works for me:

    return Paths.get(ClassLoader.getSystemResource(resourceName).toURI());
    

    Count frequency of words in a list and sort by frequency

    Try this:

    words = []
    freqs = []
    
    for line in sorted(original list): #takes all the lines in a text and sorts them
        line = line.rstrip() #strips them of their spaces
        if line not in words: #checks to see if line is in words
            words.append(line) #if not it adds it to the end words
            freqs.append(1) #and adds 1 to the end of freqs
        else:
            index = words.index(line) #if it is it will find where in words
            freqs[index] += 1 #and use the to change add 1 to the matching index in freqs
    

    Rerender view on browser resize with React

    Not sure if this is the best approach, but what worked for me was first creating a Store, I called it WindowStore:

    import {assign, events} from '../../libs';
    import Dispatcher from '../dispatcher';
    import Constants from '../constants';
    
    let CHANGE_EVENT = 'change';
    let defaults = () => {
        return {
            name: 'window',
            width: undefined,
            height: undefined,
            bps: {
                1: 400,
                2: 600,
                3: 800,
                4: 1000,
                5: 1200,
                6: 1400
            }
        };
    };
    let save = function(object, key, value) {
        // Save within storage
        if(object) {
            object[key] = value;
        }
    
        // Persist to local storage
        sessionStorage[storage.name] = JSON.stringify(storage);
    };
    let storage;
    
    let Store = assign({}, events.EventEmitter.prototype, {
        addChangeListener: function(callback) {
            this.on(CHANGE_EVENT, callback);
            window.addEventListener('resize', () => {
                this.updateDimensions();
                this.emitChange();
            });
        },
        emitChange: function() {
            this.emit(CHANGE_EVENT);
        },
        get: function(keys) {
            let value = storage;
    
            for(let key in keys) {
                value = value[keys[key]];
            }
    
            return value;
        },
        initialize: function() {
            // Set defaults
            storage = defaults();
            save();
            this.updateDimensions();
        },
        removeChangeListener: function(callback) {
            this.removeListener(CHANGE_EVENT, callback);
            window.removeEventListener('resize', () => {
                this.updateDimensions();
                this.emitChange();
            });
        },
        updateDimensions: function() {
            storage.width =
                window.innerWidth ||
                document.documentElement.clientWidth ||
                document.body.clientWidth;
            storage.height =
                window.innerHeight ||
                document.documentElement.clientHeight ||
                document.body.clientHeight;
            save();
        }
    });
    
    export default Store;
    

    Then I used that store in my components, kinda like this:

    import WindowStore from '../stores/window';
    
    let getState = () => {
        return {
            windowWidth: WindowStore.get(['width']),
            windowBps: WindowStore.get(['bps'])
        };
    };
    
    export default React.createClass(assign({}, base, {
        getInitialState: function() {
            WindowStore.initialize();
    
            return getState();
        },
        componentDidMount: function() {
            WindowStore.addChangeListener(this._onChange);
        },
        componentWillUnmount: function() {
            WindowStore.removeChangeListener(this._onChange);
        },
        render: function() {
            if(this.state.windowWidth < this.state.windowBps[2] - 1) {
                // do something
            }
    
            // return
            return something;
        },
        _onChange: function() {
            this.setState(getState());
        }
    }));
    

    FYI, these files were partially trimmed.

    Making text background transparent but not text itself

    opacity will make both text and background transparent. Use a semi-transparent background-color instead, by using a rgba() value for example. Works on IE8+

    Open file dialog and select a file using WPF controls and C#

    var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
    var result = ofd.ShowDialog();
    if (result == false) return;
    textBox1.Text = ofd.FileName;
    

    How do I import .sql files into SQLite 3?

    You can also do:

    sqlite3 database.db -init dump.sql
    

    How do I convert dmesg timestamp to custom date format?

    In recent versions of dmesg, you can just call dmesg -T.

    How to trigger ngClick programmatically

    This code will not work (throw an error when clicked):

    $timeout(function() {
       angular.element('#btn2').triggerHandler('click');
    });
    

    You need to use the querySelector as follows:

    $timeout(function() {
       angular.element(document.querySelector('#btn2')).triggerHandler('click');
    });
    

    Could not reliably determine the server's fully qualified domain name

    Here's my two cents. Maybe it's useful for future readers.

    I ran into this problem when using Apache within a Docker container. When I started a container from an image of the Apache webserver, this message appeared when I started it with docker run -it -p 80:80 my-apache-container.

    However, after starting the container in detached mode, using docker run -d -p 80:80 my-apache-container, I was able to connect through the browser.

    Convert seconds to Hour:Minute:Second

    This function my be useful, you could extend it:

    function formatSeconds($seconds) {
    
    if(!is_integer($seconds)) {
        return FALSE;
    }
    
    $fmt = "";
    
    $days = floor($seconds / 86400);
    if($days) {
        $fmt .= $days."D ";
        $seconds %= 86400;
    }
    
    $hours = floor($seconds / 3600);
    if($hours) {
        $fmt .= str_pad($hours, 2, '0', STR_PAD_LEFT).":";
        $seconds %= 3600;
    }
    
    $mins = floor($seconds / 60 );
    if($mins) {
        $fmt .= str_pad($mins, 2, '0', STR_PAD_LEFT).":";
        $seconds %= 60;
    }
    
    $fmt .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
    
    return $fmt;}
    

    Counting number of words in a file

    So easy we can get the String from files by method: getText();

    public class Main {
    
        static int countOfWords(String str) {
            if (str.equals("") || str == null) {
                return 0;
            }else{
                int numberWords = 0;
                for (char c : str.toCharArray()) {
                    if (c == ' ') {
                        numberWords++;
                    }
                }
    
                return ++numberWordss;
            }
        }
    }
    

    Override devise registrations controller

    Very simple methods Just go to the terminal and the type following

    rails g devise:controllers users //This will create devise controllers in controllers/users folder
    

    Next to use custom views

    rails g devise:views users //This will create devise views in views/users folder
    

    now in your route.rb file

    devise_for :users, controllers: {
               :sessions => "users/sessions",
               :registrations => "users/registrations" }
    

    You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.

    Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !

    Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

    1. Install Java 7u21 from: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

    2. Set these variables:

      export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home
      export PATH=$JAVA_HOME/bin:$PATH
      
    3. Run your app and have fun :)

    Request failed: unacceptable content-type: text/html using AFNetworking 2.0

    A good question always have multiple answers, to reduce and help you choose the right answer, here I am adding my own too. I have tested it and it works fine.

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.yourdomain.com/appname/data/ws/index.php/user/login/"]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"POST" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@", json);
        //Now convert json string to dictionary.
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error.localizedDescription);
    }];
    

    How can I render Partial views in asp.net mvc 3?

    <%= Html.Partial("PartialName", Model) %>
    

    Increasing Google Chrome's max-connections-per-server limit to more than 6

    There doesn't appear to be an external way to hack the behaviour of the executables.

    You could modify the Chrome(ium) executables as this information is obviously compiled in. That approach brings a lot of problems with support and automatic upgrades so you probably want to avoid doing that. You also need to understand how to make the changes to the binaries which is not something most people can pick up in a few days.

    If you compile your own browser you are creating a support issue for yourself as you are stuck with a specific revision. If you want to get new features and bug fixes you will have to recompile. All of this involves tracking Chrome development for bugs and build breakages - not something that a web developer should have to do.

    I'd follow @BenSwayne's advice for now, but it might be worth thinking about doing some of the work outside of the client (the web browser) and putting it in a background process running on the same or different machines. This process can handle many more connections and you are just responsible for getting the data back from it. Since it is local(ish) you'll get results back quickly even with minimal connections.

    JavaScript: How do I print a message to the error console?

    To answer your question you can use ES6 features,

    var var=10;
    console.log(`var=${var}`);
    

    Set Windows process (or user) memory limit

    Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.

    Otherwise it is possible to set it once for each process with the windows API

    SetProcessWorkingSetSize Function

    Regular expression to match standard 10 digit phone number

    what about multiple numbers with "+" and seperate them with ";" "," "-" or " " characters?

    Open Jquery modal dialog on click event

    $(function() {
    
    $('#clickMe').click(function(event) {
        var mytext = $('#myText').val();
    
        $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
        event.preventDefault();
    
            $("#dialog").dialog({                   
                width: 600,
                modal: true,
                close: function(event, ui) {
                    $("#dialog").hide();
                    }
                });
        }); //close click
    });
    

    Better to use .hide() instead of .remove(). With .remove() it returns undefined if you have pressed the link once, then close the modal and if you press the modal link again, it returns undefined with .remove.

    With .hide() it doesnt and it works like a breeze. Ty for the snippet in the first hand!

    Understanding the order() function

    In simple words, order() gives the locations of elements of increasing magnitude.

    For example, order(c(10,20,30)) will give 1,2,3 and order(c(30,20,10)) will give 3,2,1.

    Parsing JSON objects for HTML table

    You can use simple jQuery jPut plugin

    http://plugins.jquery.com/jput/

    <script>
    $(document).ready(function(){
    
    var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
    //while running this code the template will be appended in your div with json data
    $("#tbody").jPut({
        jsonData:json,
        //ajax_url:"youfile.json",  if you want to call from a json file
        name:"tbody_template",
    });
    
    });
    </script>   
    
    <div jput="tbody_template">
     <tr>
      <td>{{name}}</td>
      <td>{{score}}</td>
     </tr>
    </div>
    
    <table>
     <tbody id="tbody">
     </tbody>
    </table>
    

    javascript: pause setTimeout();

    If anyone wants the TypeScript version shared by the Honorable @SeanVieira here, you can use this:

        public timer(fn: (...args: any[]) => void, countdown: number): { onCancel: () => void, onPause: () => void, onResume: () => void } {
            let ident: NodeJS.Timeout | number;
            let complete = false;
            let totalTimeRun: number;
            const onTimeDiff = (date1: number, date2: number) => {
                return date2 ? date2 - date1 : new Date().getTime() - date1;
            };
    
            const handlers = {
                onCancel: () => {
                    clearTimeout(ident as NodeJS.Timeout);
                },
                onPause: () => {
                    clearTimeout(ident as NodeJS.Timeout);
                    totalTimeRun = onTimeDiff(startTime, null);
                    complete = totalTimeRun >= countdown;
                },
                onResume: () => {
                    ident = complete ? -1 : setTimeout(fn, countdown - totalTimeRun);
                }
            };
    
            const startTime = new Date().getTime();
            ident = setTimeout(fn, countdown);
    
            return handlers;
        }
    

    Add a tooltip to a div

    A CSS3-only solution could be:

    CSS3:

    div[id^="tooltip"]:after {content: attr(data-title); background: #e5e5e5; position: absolute; top: -10px; left:  0; right: 0; z-index: 1000;}
    

    HTML5:

    <div style="background: yellow;">
        <div id="tooltip-1" data-title="Tooltip Text" style="display: inline-block; position: relative; background: pink;">
            <label>Name</label>
            <input type="text" />
        </div>
    </div>
    

    You could then create a tooltip-2 div the same way... you can of course also use the title attribute instead of data attribute.

    Apply style ONLY on IE

    <!--[if !IE]><body<![endif]-->
    <!--[if IE]><body class="ie"> <![endif]-->
    
    body.ie .actual-form table {
        width: 100%
    }
    

    Why does the C++ STL not provide any "tree" containers?

    Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.

    Some issues to consider:

    • Are the number of children for a node fixed or variable?
    • How much overhead per node? - ie, do you need parent pointers, sibling pointers, etc.
    • What algorithms to provide? - different iterators, search algorithms, etc.

    In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, Boost Graph Library is essentially a superset of what a tree library could be used for.

    Here are some other generic tree implementations:

    How to integrate sourcetree for gitlab

    Sourcetree 3.x has an option to accept gitLab. See here. I now use Sourcetree 3.0.15. In Settings, put your remote gitLab host and url, etc. If your existing git client version is not supported any more, the easiest way is perhaps to use Sourcetree embedded Git by Tools->Options->Git, in Git Version near the bottom, choose Embedded. A download may happen.

    How to populate a dropdownlist with json data in jquery?

    //javascript
    //teams.Table does not exist
    
    function OnSuccessJSON(data, status) {
        var teams = eval('(' + data.d + ')');
        var listItems = "";
        for (var i = 0; i < teams.length; i++) {
          listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
        }
        $("#<%=ddlTeams.ClientID%>").html(listItems);
    } 
    

    Change one value based on another value in pandas

    One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.

    Assuming you can load your data directly into pandas with pandas.read_csv then the following code might be helpful for you.

    import pandas
    df = pandas.read_csv("test.csv")
    df.loc[df.ID == 103, 'FirstName'] = "Matt"
    df.loc[df.ID == 103, 'LastName'] = "Jones"
    

    As mentioned in the comments, you can also do the assignment to both columns in one shot:

    df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'
    

    Note that you'll need pandas version 0.11 or newer to make use of loc for overwrite assignment operations.


    Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:

    import pandas
    df = pandas.read_csv("test.csv")
    df['FirstName'][df.ID == 103] = "Matt"
    df['LastName'][df.ID == 103] = "Jones"
    

    Overlapping Views in Android

    Visible gallery changes visibility which is how you get the gallery over other view overlap. the Home sample app has some good examples of this technique.

    Are global variables bad?

    Global variables are fine in small programs, but horrible if used the same way in large ones.

    This means that you can easily get in the habit of using them while learning. This is what your professor is trying to protect you from.

    When you are more experienced it will be easier to learn when they are okay.

    How to loop backwards in python?

    To reverse a string without using reversed or [::-1], try something like:

    def reverse(text):
        # Container for reversed string
        txet=""
    
        # store the length of the string to be reversed
        # account for indexes starting at 0
        length = len(text)-1
    
        # loop through the string in reverse and append each character
        # deprecate the length index
        while length>=0:
            txet += "%s"%text[length]
            length-=1
        return txet
    

    How often should you use git-gc?

    You don't have to use git gc very often, because git gc (Garbage collection) is run automatically on several frequently used commands:

    git pull
    git merge
    git rebase
    git commit
    

    Source: git gc best practices and FAQS

    How to split CSV files as per number of rows specified?

    I have a one-liner answer (this example gives you 999 lines of data and one header row per file)

    cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'
    

    https://stackoverflow.com/a/53062251/401226

    Python strftime - date without leading 0?

    simply use replace like this:

    (datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")

    it will output:

    '2017/7/21'