Programs & Examples On #Lines of code

The number of code lines. Can be used as a metric.

How do you count the lines of code in a Visual Studio solution?

cloc is an excellent commandline, Perl-based, Windows-executable which will break down the blank lines, commented lines, and source lines of code, grouped by file-formats.

Now it won't specifically run on a VS solution file, but it can recurse through directories, and you can set up filename filters as you see fit.

Here's the sample output from their web page:


prompt> cloc perl-5.10.0.tar.gz
    4076 text files.
    3883 unique files.                                          
    1521 files ignored.

http://cloc.sourceforge.net v 1.07  T=10.0 s (251.0 files/s, 84566.5 lines/s)
-------------------------------------------------------------------------------
Language          files     blank   comment      code    scale   3rd gen. equiv
-------------------------------------------------------------------------------
Perl               2052    110356    112521    309778 x   4.00 =     1239112.00
C                   135     18718     22862    140483 x   0.77 =      108171.91
C/C++ Header        147      7650     12093     44042 x   1.00 =       44042.00
Bourne Shell        116      3402      5789     36882 x   3.81 =      140520.42
Lisp                  1       684      2242      7515 x   1.25 =        9393.75
make                  7       498       473      2044 x   2.50 =        5110.00
C++                  10       312       277      2000 x   1.51 =        3020.00
XML                  26       231         0      1972 x   1.90 =        3746.80
yacc                  2       128        97      1549 x   1.51 =        2338.99
YAML                  2         2         0       489 x   0.90 =         440.10
DOS Batch            11        85        50       322 x   0.63 =         202.86
HTML                  1        19         2        98 x   1.90 =         186.20
-------------------------------------------------------------------------------
SUM:               2510    142085    156406    547174 x   2.84 =     1556285.03
-------------------------------------------------------------------------------

The third generation equivalent scale is a rough estimate of how much code it would take in a third generation language. Not terribly useful, but interesting anyway.

How to use Google fonts in React.js?

It could be the self-closing tag of link at the end, try:

<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet"/> 

and in your main.css file try:

body,div {
  font-family: 'Bungee Inline', cursive;
}

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

Assign format of DateTime with data annotations?

Did you try this?

[DataType(DataType.Date)]

sorting integers in order lowest to highest java

if array.sort doesn't have what your looking for you can try this:

package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
    ArrayList<AffineTransform> affs;
    ListIterator<AffineTransform> li;
    Integer count, count2;
    /**
     * @param args
     */
    public static void main(String[] args) {
        new QuicksortAlgorithm();
    }
    public QuicksortAlgorithm(){
        count = new Integer(0);
        count2 = new Integer(1);
        affs = new ArrayList<AffineTransform>();
        for (int i = 0; i <= 128; i++){
            affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
        }
        affs = arrangeNumbers(affs);
        printNumbers();
    }
    public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
        while (list.size() > 1 && count != list.size() - 1){
            if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
                list.add(count, list.get(count2));
                list.remove(count2 + 1);
            }
            if (count2 == list.size() - 1){
                count++;
                count2 = count + 1;
            }
            else{
            count2++;
            }
        }
        return list;
    }
    public void printNumbers(){
        li = affs.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
    }
}

SyntaxError: Unexpected token function - Async Await Nodejs

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

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

in the following file

package.json

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

How do I add a bullet symbol in TextView?

You have to use the right character encoding to accomplish this effect. You could try with &#8226;


Update

Just to clarify: use setText("\u2022 Bullet"); to add the bullet programmatically. 0x2022 = 8226

Side-by-side list items as icons within a div (css)

give the LI float: left (or right)

They will all be in the same line until there will be no more room in the container (your case, a ul). (forgot): If you have a block element after the floating elements, he will also stick to them, unless you give him a clear:both, OR put an empty div before it with clear:both

What does functools.wraps do?

this is the source code about wraps:

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')

WRAPPER_UPDATES = ('__dict__',)

def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):

    """Update a wrapper function to look like the wrapped function

       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        setattr(wrapper, attr, getattr(wrapped, attr))
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    """Decorator factory to apply update_wrapper() to a wrapper function

   Returns a decorator that invokes update_wrapper() with the decorated
   function as the wrapper argument and the arguments to wraps() as the
   remaining arguments. Default arguments are as for update_wrapper().
   This is a convenience function to simplify applying partial() to
   update_wrapper().
    """
    return partial(update_wrapper, wrapped=wrapped,
                   assigned=assigned, updated=updated)

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

It is hard to get pip working on El Capitan for several reasons:

  1. OS X doesn't set some distutils variables correctly, so pip tries to install ancillary files in locations under /System/Library/. El Capitan blocks this, which is the error you are running into.
  2. OS X includes a number of outdated packages under /System/Library/. pip often wants to upgrade these but cannot on El Capitan.
  3. OS X places /System/Library/ higher in the python search order than /Library/Python/2.7/site-packages (the system-wide python package location), so even if you manage to install newer versions of some packages, the old ones still get loaded, breaking some dependencies.

There are workarounds for all of these at https://apple.stackexchange.com/a/223163/143849 . But you may be best off installing your own version of Python via the standard Python installer, Homebrew or Anaconda.

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Linq to SQL how to do "where [column] in (list of values)"

I had been using the method in Jon Skeet's answer, but another one occurred to me using Concat. The Concat method performed slightly better in a limited test, but it's a hassle and I'll probably just stick with Contains, or maybe I'll write a helper method to do this for me. Either way, here's another option if anyone is interested:

The Method

// Given an array of id's
var ids = new Guid[] { ... };

// and a DataContext
var dc = new MyDataContext();

// start the queryable
var query = (
    from thing in dc.Things
    where thing.Id == ids[ 0 ]
    select thing 
);

// then, for each other id
for( var i = 1; i < ids.Count(); i++ ) {
    // select that thing and concat to queryable
    query.Concat(
        from thing in dc.Things
        where thing.Id == ids[ i ]
        select thing
    );
}

Performance Test

This was not remotely scientific. I imagine your database structure and the number of IDs involved in the list would have a significant impact.

I set up a test where I did 100 trials each of Concat and Contains where each trial involved selecting 25 rows specified by a randomized list of primary keys. I've run this about a dozen times, and most times the Concat method comes out 5 - 10% faster, although one time the Contains method won by just a smidgen.

ASP.NET MVC: No parameterless constructor defined for this object

This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:

public class MyViewModel
{
    public SelectList Contacts { get;set; }
}

You'll need to refactor your model to do it a different way if this is the cause. So using an IEnumerable<Contact> and writing an extension method that creates the drop down list with the different property definitions:

public class MyViewModel
{
    public Contact SelectedContact { get;set; }
    public IEnumerable<Contact> Contacts { get;set; }
}

public static MvcHtmlString DropDownListForContacts(this HtmlHelper helper, IEnumerable<Contact> contacts, string name, Contact selectedContact)
{
    // Create a List<SelectListItem>, populate it, return DropDownList(..)
}

Or you can use the @Mark and @krilovich approach, just need replace SelectList to IEnumerable, it's works with MultiSelectList too.

 public class MyViewModel
    {
        public Contact SelectedContact { get;set; }
        public IEnumerable<SelectListItem> Contacts { get;set; }
    }

Create two-dimensional arrays and access sub-arrays in Ruby

You didn't state your actual goal, but maybe this can help:

require 'matrix'  # bundled with Ruby
m = Matrix[
 [1, 2, 3],
 [4, 5, 6]
]

m.column(0) # ==> Vector[1, 4]

(and Vectors acts like arrays)

or, using a similar notation as you desire:

m.minor(0..1, 2..2) # => Matrix[[3], [6]]

Beamer: How to show images as step-by-step images

This is a sample code I used to counter the problem.

\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}

fork() child and parent processes

It is printing twice because you are calling printf twice, once in the execution of your program and once in the fork. Try taking your fork() out of the printf call.

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Laravel Blade html image

Had the same problem with laravel 5.3... This is how I did it and very easy. for example logo in the blade page view

****<image img src="/img/logo.png" alt="Logo"></image>****

When is del useful in Python?

Every object in python has an identifier, Type, reference count associated with it, when we use del the reference count is reduced, when the reference count becomes zero it is a potential candidate for getting garbage collected. This differentiates the del when compared to setting an identifier to None. In later case it simply means the object is just left out wild( until we are out of scope in which case the count is reduced) and simply now the identifier point to some other object(memory location).

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

There is no reason you should not be able to delete this file. I would look to see who has a hold on this file. In unix/linux, you can use the lsof utility to check which process has a lock on the file. In windows, you can use process explorer.

for lsof, it's as simple as saying:

lsof /path/and/name/of/the/file

for process explorer you can use the find menu and enter the file name to show you the handle which will point you to the process locking the file.

here is some code that does what I think you need to do:

FileOutputStream to;

try {
    String file = "/tmp/will_delete.txt";
    to = new FileOutputStream(file );
    to.write(new String("blah blah").getBytes());
    to.flush();
    to.close();
    File f = new File(file);
    System.out.print(f.delete());
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

It works fine on OS X. I haven't tested it on windows but I suspect it should work on Windows too. I will also admit seeing some unexpected behavior on Windows w.r.t. file handling.

How to execute raw SQL in Flask-SQLAlchemy app

You can get the results of SELECT SQL queries using from_statement() and text() as shown here. You don't have to deal with tuples this way. As an example for a class User having the table name users you can try,

from sqlalchemy.sql import text

user = session.query(User).from_statement(
    text("""SELECT * FROM users where name=:name""")
).params(name="ed").all()

return user

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

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

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

Property 'map' does not exist on type 'Observable<Response>'

just install rxjs-compat by typing in terminal:

npm install --save rxjs-compat

then import :

import 'rxjs/Rx';

Rails formatting date

Since I18n is the Rails core feature starting from version 2.2 you can use its localize-method. By applying the forementioned strftime %-variables you can specify the desired format under config/locales/en.yml (or whatever language), in your case like this:

time:
  formats:
    default: '%FT%T'

Or if you want to use this kind of format in a few specific places you can refer it as a variable like this

time:
  formats:
    specific_format: '%FT%T'

After that you can use it in your views like this:

l(Mode.last.created_at, format: :specific_format)  

Remove local git tags that are no longer on the remote repository

If you only want those tags which exist on the remote, simply delete all your local tags:

$ git tag -d $(git tag)

And then fetch all the remote tags:

$ git fetch --tags

Vertical Align Center in Bootstrap 4

In Bootstrap 4 (beta), use align-middle. Refer to Bootstrap 4 Documentation on Vertical alignment:

Change the alignment of elements with the vertical-alignment utilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cell elements.

Choose from .align-baseline, .align-top, .align-middle, .align-bottom, .align-text-bottom, and .align-text-top as needed.

AttributeError: can't set attribute in python

For those searching this error, another thing that can trigger AtributeError: can't set attribute is if you try to set a decorated @property that has no setter method. Not the problem in the OP's question, but I'm putting it here to help any searching for the error message directly. (if you don't like it, go edit the question's title :)

class Test:
    def __init__(self):
        self._attr = "original value"
        # This will trigger an error...
        self.attr = "new value"
    @property
    def attr(self):
        return self._attr

Test()

What is the exact meaning of Git Bash?

I think the question asker is (was) thinking that git bash is a command like git init or git checkout. Git bash is not a command, it is an interface. I will also assume the asker is not a linux user because bash is very popular the unix/linux world. The name "bash" is an acronym for "Bourne Again SHell". Bash is a text-only command interface that has features which allow automated scripts to be run. A good analogy would be to compare bash to the new PowerShell interface in Windows7/8. A poor analogy (but one likely to be more readily understood by more people) is the combination of the command prompt and .BAT (batch) command files from the days of DOS and early versions of Windows.

REFERENCES:

Joining 2 SQL SELECT result sets into one

SELECT table1.col_a, table1.col_b, table2.col_c 
  FROM table1 
  INNER JOIN table2 ON table1.col_a = table2.col_a

Python - Passing a function into another function

Just pass it in, like this:

Game(list_a, list_b, Rule1)

and then your Game function could look something like this (still pseudocode):

def Game(listA, listB, rules=None):
    if rules:
        # do something useful
        # ...
        result = rules(variable) # this is how you can call your rule
    else:
        # do something useful without rules

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

Setting Django up to use MySQL

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

Getting a list of files in a directory with a glob

I won't pretend to be an expert on the topic, but you should have access to both the glob and wordexp function from objective-c, no?

Laravel 5 Clear Views Cache

Here is a helper that I wrote to solve this issue for my projects. It makes it super simple and easy to be able to clear everything out quickly and with a single command.

https://github.com/Traqza/clear-everything

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Honestly I didnt bother to deal with the grants and this worked even without the privileges:

echo "select * from employee" | mysql --host=HOST --port=PORT --user=UserName --password=Password DATABASE.SCHEMA > output.txt

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

CMake not able to find OpenSSL library

sudo apt install libssl-dev works on ubuntu 18.04.

How to force table cell <td> content to wrap?

Use table-layout:fixed in the table and word-wrap:break-word in the td.

See this example:

<html>
<head>
   <style>
   table {border-collapse:collapse; table-layout:fixed; width:310px;}
   table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
   </style>
</head>

<body>
   <table>
      <tr>
         <td>1</td>
         <td>Lorem Ipsum</td>
         <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>
      </tr>
      <tr>
         <td>2</td>
         <td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>
         <td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>
      </tr>
      <tr>
         <td>3</td>
         <td></td>
         <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>
      </tr>
   </table>
</body>
</html>

DEMO:

_x000D_
_x000D_
table {border-collapse:collapse; table-layout:fixed; width:310px;}_x000D_
       table td {border:solid 1px #fab; width:100px; word-wrap:break-word;}
_x000D_
       <table>_x000D_
          <tr>_x000D_
             <td>1</td>_x000D_
             <td>Lorem Ipsum</td>_x000D_
             <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
             <td>2</td>_x000D_
             <td>LoremIpsumhasbeentheindustry'sstandarddummytexteversincethe1500s,whenanunknown</td>_x000D_
             <td>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
             <td>3</td>_x000D_
             <td></td>_x000D_
             <td>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna...</td>_x000D_
          </tr>_x000D_
       </table>_x000D_
    
_x000D_
_x000D_
_x000D_

MS-access reports - The search key was not found in any record - on save

Another possible cause of this error is a mismatched workgroup file. That is, if you try to use a secured (or partially-secured) MDB with a workgroup file other than the one used to secure it, you can trigger the error (I've seen it myself, years ago with Access 2000).

What is the maximum float in Python?

For all practical purposes, and with no import at all, one can use:

x = float("inf")

More detail on this related question: How can I represent an infinite number in Python?

Write a formula in an Excel Cell using VBA

The correct character (comma or colon) depends on the purpose.

Comma (,) will sum only the two cells in question.

Colon (:) will sum all the cells within the range with corners defined by those two cells.

Disable Tensorflow debugging information

You can disable all debugging logs using os.environ :

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

Tested on tf 0.12 and 1.0

In details,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

How can I make a checkbox readonly? not disabled?

Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/

C Linking Error: undefined reference to 'main'

You're not including the C file that contains main() when compiling, so the linker isn't seeing it.

You need to add it:

$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp

Check if number is decimal

You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):

function is_decimal( $val )
{
    return is_numeric( $val ) && floor( $val ) != $val;
}

Can't perform a React state update on an unmounted component

Inspired by the accepted answer by @ford04 I had even better approach dealing with it, instead of using useEffect inside useAsync create a new function that returns a callback for componentWillUnmount :

function asyncRequest(asyncRequest, onSuccess, onError, onComplete) {
  let isMounted=true
  asyncRequest().then((data => isMounted ? onSuccess(data):null)).catch(onError).finally(onComplete)
  return () => {isMounted=false}
}

...

useEffect(()=>{
        return asyncRequest(()=>someAsyncTask(arg), response=> {
            setSomeState(response)
        },onError, onComplete)
    },[])

Angular 2 Scroll to top on Route Change

You can register a route change listener on your main component and scroll to top on route changes.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}

How can you use optional parameters in C#?

You could use method overloading...

GetFooBar()
GetFooBar(int a)
GetFooBar(int a, int b)

It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.

You could use Nullable types...

GetFooBar(int? a, int? b)

You could then check, using a.HasValue, to see if a parameter has been set.

Another option would be to use a 'params' parameter.

GetFooBar(params object[] args)

If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

How do I supply an initial value to a text field?

If you want to handle multiple TextInputs as asked by @MRT in the comment to the accepted answer, you can create a function that takes an initial value and returns a TextEditingController like this:

initialValue(val) {
  return TextEditingController(text: val);
}

Then, set this function as the controller for the TextInput and supply its initial value there like this:

controller: initialValue('Some initial value here....')

You can repeat this for the other TextInputs.

How to delete all files from a specific folder?

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);

Or in a single line:

Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);

Create a Date with a set timezone without using a string representation

The easiest way that I have found to get the correct date is using datejs.

http://www.datejs.com/

I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'

var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
    yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);

Console will read:

Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)

Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)

https://jsfiddle.net/vp1ena7b/3/

The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.

I thought that this might help someone...

How to spyOn a value property (rather than a method) with Jasmine

The right way to do this is with the spy on property, it will allow you to simulate a property on an object with an specific value.

const spy = spyOnProperty(myObj, 'valueA').and.returnValue(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();

Extract csv file specific columns to list in Python

import csv
from sys import argv

d = open("mydata.csv", "r")

db = []

for line in csv.reader(d):
    db.append(line)

# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.

Align div with fixed position on the right side

Just do this. It doesn't affect the horizontal position.

.test {
 position: fixed;
 left: 0;
 right: 0;
 }

How to use basic authorization in PHP curl

$headers = array(
    'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

HTML5: Slider with two inputs possible?

No, the HTML5 range input only accepts one input. I would recommend you to use something like the jQuery UI range slider for that task.

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

Go to the task manager, kill the java processes and turn the server back on. should work fine.

How to integrate SAP Crystal Reports in Visual Studio 2017

I had exactly the same problem with my VS 2013 solutions when I install VS 2017 and Crystal Reports SP21. In fact it's because VS does not necessarily convert the solution in the first launch.

Once you have installed Crystal Report SP 21, make sure that VS 2017 upgrade your solution : a window must appear "SAP Crystal Reports, version for Visual" with a radio button "Convert the solution".

Screenshot in french :

enter image description here

When I used the menu "File / Open / Project/Solution", the conversion was not done.

I have to do that :

  1. Add VS 2017 on the tasks bar
  2. Run VS 2017 and Open the solution with File menu
  3. Try to build the project, errors appear with Crystal Reports
  4. Close VS 2017
  5. Right click on VS 2017 shortcur in then tasks bar and open the solution directly
  6. The conversion run this time, you can open .rpt and the solution build without error.

Why does javascript map function return undefined?

My solution would be to use filter after the map.

This should support every JS data type.

example:

const notUndefined = anyValue => typeof anyValue !== 'undefined'    
const noUndefinedList = someList
          .map(// mapping condition)
          .filter(notUndefined); // by doing this, 
                      //you can ensure what's returned is not undefined

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

**this is first  part of program**
<head runat="server">
    <title></title>
    <style>
        .style4
        {
            margin-left:90px;
        }
        .style3{
            margin-left:130px;
        }
        .style2{
            color:white;
            margin-left:100px;
            height:400px;
            width:450px;
            text-align:left;
                }
        .style1{
            height:450px;
            width:550px;
            margin-left:450px;
            margin-top:100px;
            margin-right:500px;
            background-color:rgba(0,0,0,0.9);
        }
        body{
            margin:0;
            padding:0;
        }
        body{
            background-image:url("/stock/50.jpg");
            background-size:cover;
            background-repeat:no-repeat;
            }   
       </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <div class="style1">
                <table class="style2">
                   <tr>
                       <td colspan="2"><h1 class="style4">Sending Email</h1></td>
                   </tr>
                   <tr>
                       <td>To</td>
                       <td><asp:TextBox ID="txtto" runat="server" Height="20px" Width="250px" placeholder="[email protected]"></asp:TextBox><asp:RequiredFieldValidator ForeColor="Red" runat="server" ErrorMessage="Required" ControlToValidate="txtto" Display="Dynamic"></asp:RequiredFieldValidator><asp:RegularExpressionValidator runat="server" ForeColor="Red" ControlToValidate="txtto" Display="Dynamic" ErrorMessage="Invalid Email_ID" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator> </td>
                   </tr>
                     <tr>
                       <td>From</td>
                       <td><asp:TextBox ID="txtfrom" runat="server" Height="20px" Width="250px" placeholder="[email protected]"></asp:TextBox> <asp:RequiredFieldValidator ForeColor="Red" Display="Dynamic" runat="server" ErrorMessage="Required" ControlToValidate="txtfrom"></asp:RequiredFieldValidator>
                           <asp:RegularExpressionValidator Display="Dynamic" runat="server" ErrorMessage="Invalid Email-ID" ControlToValidate="txtfrom" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                         </td>
                   </tr>
                     <tr>
                       <td>Subject</td>
                       <td><asp:TextBox ID="txtsubject" runat="server" Height="20px" Width="250px" placeholder="Demonstration on Youtube"></asp:TextBox><asp:RequiredFieldValidator ForeColor="Red" runat="server" ErrorMessage="Required" ControlToValidate="txtsubject"></asp:RequiredFieldValidator> </td>
                   </tr>
                     <tr>
                       <td>Body</td>
                       <td><asp:TextBox ID="txtbody" runat="server" Width="250px" TextMode="MultiLine" Rows="5" placeholder="This is the body text"></asp:TextBox><asp:RequiredFieldValidator ForeColor="Red" runat="server" ErrorMessage="Required" ControlToValidate="txtbody"></asp:RequiredFieldValidator> </td>
                   </tr>
                     <tr>
                       <td colspan="2"><asp:Button CssClass="style3" BackColor="Green" BorderColor="green" ID="send" Text="Send" runat="server" Height="30px"  Width="100px" OnClick="send_Click"/></td>
                     </tr>
                    <tr>
                        <td colspan="2"><asp:Label ID="lblmessage" runat="server"></asp:Label> </td>
                    </tr>
               </table>
            </div>

        </div>
    </form>
</body>
</html>


**this is second part of program**

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

namespace WebApplication6
{
    public partial class sendingemail1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void send_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage message = new MailMessage();
                message.To.Add(txtto.Text);
                message.Subject = txtsubject.Text;
                message.Body = txtbody.Text;
                message.From = new MailAddress(txtfrom.Text);
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential(txtfrom.Text, "Sunil@123");
                for(int i=1;i<=100;i++)
                { 
                client.Send(message);
                lblmessage.Text = "Mail Successfully send";
                }
            }
            catch (Exception ex)
            {
                lblmessage.Text = ex.Message;
            }
        }
    }
}

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Download a file from NodeJS Server using Express

For static files like pdfs, Word docs, etc. just use Express's static function in your config:

// Express config
var app = express().configure(function () {
    this.use('/public', express.static('public')); // <-- This right here
});

And then just put all your files inside that 'public' folder, for example:

/public/docs/my_word_doc.docx

And then a regular old link will allow the user to download it:

<a href="public/docs/my_word_doc.docx">My Word Doc</a>

Multiple lines of input in <input type="text" />

If you are using React, the library material-ui.com can help you with:

  <FormControl>
    <InputLabel htmlFor="textContract">{`textContract`}</InputLabel>
    <Input
      id="textContract"
      multiline
      rows="30"
      type="text"
      value={props.textContract}
      onChange={() => {}}
    />
  </FormControl>

https://material-ui.com/components/text-fields/#multiline

Eclipse/Java code completion not working

Just in case anyone got to a desperate point where nothing works... It happened to us that the content assist somehow shrunk so no suggestion was shown, just the "Press Ctrl+Space for non-Java..." could be seen. So, it was just a matter of dragging the corner of the content assist to enlarge the pop-up.

I know, embarrassing. Hope it helps.

Note: this was an Ubuntu server with Xfce4 using Eclipse Oxygen.

How to change the default GCC compiler in Ubuntu?

As @Tommy suggested, you should use update-alternatives.
It assigns values to every software of a family, so that it defines the order in which the applications will be called.

It is used to maintain different versions of the same software on a system. In your case, you will be able to use several declinations of gcc, and one will be favoured.

To figure out the current priorities of gcc, type in the command pointed out by @tripleee's comment:

update-alternatives --query gcc

Now, note the priority attributed to gcc-4.4 because you'll need to give a higher one to gcc-3.3.
To set your alternatives, you should have something like this (assuming your gcc installation is located at /usr/bin/gcc-3.3, and gcc-4.4's priority is less than 50):

update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-3.3 50

--edit--

Finally, you can also use the interactive interface of update-alternatives to easily switch between versions. Type update-alternatives --config gcc to be asked to choose the gcc version you want to use among those installed.

--edit 2 --

Now, to fix the CXX environment variable systemwide, you need to put the line indicated by @DipSwitch's in your .bashrc file (this will apply the change only for your user, which is safer in my opinion):

echo 'export CXX=/usr/bin/gcc-3.3' >> ~/.bashrc

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

How do I get a button to open another activity?

Using an OnClickListener

Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

Button yourButton = (Button) findViewById(R.id.your_buttons_id);

yourButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v){                        
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
});

This is probably most developers preferred method. However, there is a common alternative.

Using onClick in XML

Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

public void yourMethodName(View v){
    startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}

Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

References;

simple way to display data in a .txt file on a webpage?

You can add it as script file. save the txt file with js suffix

in the head section add

_x000D_
_x000D_
<script src="fileName.js"></script>
_x000D_
_x000D_
_x000D_

Laravel: Validation unique on update

Very easy to do it ,

Write it at your controller

$this->validate($request,[
     'email'=>['required',Rule::unique('yourTableName')->ignore($request->id)]
]);
Note : Rule::unique('yourTableName')->ignore($idParameter) , here $idParameter you can receive from get url also you can get it from hidden field.
Most important is don't forget to import Rule at the top.

How to iterate through a list of dictionaries in Jinja template?

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

Convert from List into IEnumerable format

As far as I know List<T> implements IEnumerable<T>. It means that you do not have to convert or cast anything.

AngularJS - pass function to directive

How about passing the controller function with bidirectional binding? Then you can use it in the directive exactly the same way as in a regular template (I stripped irrelevant parts for simplicity):

<div ng-controller="testCtrl">

   <!-- pass the function with no arguments -->
   <test color1="color1" update-fn="updateFn"></test>
</div>

<script>
   angular.module('dr', [])
   .controller("testCtrl", function($scope) {
      $scope.updateFn = function(msg) {
         alert(msg);
      }
   })
   .directive('test', function() {
      return {
         scope: {
            updateFn: '=' // '=' bidirectional binding
         },
         template: "<button ng-click='updateFn(1337)'>Click</button>"
      }
   });
</script>

I landed at this question, because I tried the method above befire, but somehow it didn't work. Now it works perfectly.

Close application and launch home screen on Android

Short answer: call moveTaskToBack(true) on your Activity instead of System.exit(). This will hide your application until the user wants to use it again.

The longer answer starts with another question: why do you want to kill your application?

The Android OS handles memory management and processes and so on so my advice is just let Android worry about this for you. If the user wants to leave your application they can press the Home button and your application will effectively disappear. If the phone needs more memory later the OS will terminate your application then.

As long as you're responding to lifecycle events appropriately, neither you nor the user needs to care if your application is still running or not.

So if you want to hide your application call moveTaskToBack() and let Android decide when to kill it.

How to listen for changes to a MongoDB collection?

What you are thinking of sounds a lot like triggers. MongoDB does not have any support for triggers, however some people have "rolled their own" using some tricks. The key here is the oplog.

When you run MongoDB in a Replica Set, all of the MongoDB actions are logged to an operations log (known as the oplog). The oplog is basically just a running list of the modifications made to the data. Replicas Sets function by listening to changes on this oplog and then applying the changes locally.

Does this sound familiar?

I cannot detail the whole process here, it is several pages of documentation, but the tools you need are available.

First some write-ups on the oplog - Brief description - Layout of the local collection (which contains the oplog)

You will also want to leverage tailable cursors. These will provide you with a way to listen for changes instead of polling for them. Note that replication uses tailable cursors, so this is a supported feature.

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

This Proxy will expose the buffer as any of the TypedArrays, without any copy. :

https://www.npmjs.com/package/node-buffer-as-typedarray

It only works on LE, but can be easily ported to BE. Also, never got to actually test how efficient this is.

Cell spacing in UICollectionView

Answer for Swift 3.0, Xcode 8

1.Make sure you set collection view delegate

class DashboardViewController: UIViewController {
    @IBOutlet weak var dashboardCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        dashboardCollectionView.delegate = self
    }
}

2.Implement UICollectionViewDelegateFlowLayout protocol, not UICollectionViewDelegate.

extension DashboardViewController: UICollectionViewDelegateFlowLayout {
    fileprivate var sectionInsets: UIEdgeInsets {
        return .zero
    }

    fileprivate var itemsPerRow: CGFloat {
        return 2
    }

    fileprivate var interitemSpace: CGFloat {
        return 5.0
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionPadding = sectionInsets.left * (itemsPerRow + 1)
        let interitemPadding = max(0.0, itemsPerRow - 1) * interitemSpace
        let availableWidth = collectionView.bounds.width - sectionPadding - interitemPadding
        let widthPerItem = availableWidth / itemsPerRow

        return CGSize(width: widthPerItem, height: widthPerItem)
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return sectionInsets
    }

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return interitemSpace
    }
}

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Efficient way to remove ALL whitespace from String?

I found a nice write-up on this on CodeProject by Felipe Machado (with help by Richard Robertson)

He tested ten different methods. This one is the fastest unsafe version...

public static unsafe string TrimAllWithStringInplace(string str) {
    fixed (char* pfixed = str) {
        char* dst = pfixed;
        for (char* p = pfixed; *p != 0; p++)

            switch (*p) {

                case '\u0020': case '\u00A0': case '\u1680': case '\u2000': case '\u2001':

                case '\u2002': case '\u2003': case '\u2004': case '\u2005': case '\u2006':

                case '\u2007': case '\u2008': case '\u2009': case '\u200A': case '\u202F':

                case '\u205F': case '\u3000': case '\u2028': case '\u2029': case '\u0009':

                case '\u000A': case '\u000B': case '\u000C': case '\u000D': case '\u0085':
                    continue;

                default:
                    *dst++ = *p;
                    break;
            }

        return new string(pfixed, 0, (int)(dst - pfixed));
    }
}

And the fastest safe version...

public static string TrimAllWithInplaceCharArray(string str) {

    var len = str.Length;
    var src = str.ToCharArray();
    int dstIdx = 0;

    for (int i = 0; i < len; i++) {
        var ch = src[i];

        switch (ch) {

            case '\u0020': case '\u00A0': case '\u1680': case '\u2000': case '\u2001':

            case '\u2002': case '\u2003': case '\u2004': case '\u2005': case '\u2006':

            case '\u2007': case '\u2008': case '\u2009': case '\u200A': case '\u202F':

            case '\u205F': case '\u3000': case '\u2028': case '\u2029': case '\u0009':

            case '\u000A': case '\u000B': case '\u000C': case '\u000D': case '\u0085':
                continue;

            default:
                src[dstIdx++] = ch;
                break;
        }
    }
    return new string(src, 0, dstIdx);
}

There are also some nice independent benchmarks on Stack Overflow by Stian Standahl that also show how Felipe's function is about 300% faster than the next fastest function.

How to re-enable right click so that I can inspect HTML elements in Chrome?

You could use javascript:void(document.oncontextmenu=null); open Browser console and run the code above. It will turn off blockin' of mouse right button

How to pass text in a textbox to JavaScript function?

You can get textbox value and Id by the following simple example in dotNet programming

<html>
        <head>
         <script type="text/javascript">
             function GetTextboxId_Value(textBox) 
                 {
                 alert(textBox.value);    // To get Text Box Value(Text)
                 alert(textBox.id);      // To get Text Box Id like txtSearch
             }
         </script>     
        </head>
 <body>
 <input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" />  </body>
 </html>

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

Concatenating strings in Razor

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

AttributeError: 'module' object has no attribute 'urlopen'

To get 'dataX = urllib.urlopen(url).read()' working in python3 (this would have been correct for python2) you must just change 2 little things.

1: The urllib statement itself (add the .request in the middle):

dataX = urllib.request.urlopen(url).read()

2: The import statement preceding it (change from 'import urlib' to:

import urllib.request

And it should work in python3 :)

Difference between break and continue in PHP?

For the Record:

Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

How to vertically center content with variable height within a div?

you can use flex display such as below code:

_x000D_
_x000D_
.example{_x000D_
  background-color:red;_x000D_
  height:90px;_x000D_
  width:90px;_x000D_
  display:flex;_x000D_
  align-items:center; /*for vertically center*/_x000D_
  justify-content:center; /*for horizontally center*/_x000D_
}
_x000D_
<div class="example">_x000D_
    <h6>Some text</h6>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

how to assign a block of html code to a javascript variable

you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.

var html = {
  top_crimes_template:
    [
      '<div class="top_crimes"><h3>Top Crimes</h3></div>',
      '<table class="crimes-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Crime:</span>',
          '</th>',
          '<th>',
            '<span id="last_crime_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join(""),
  top_teams_template:
    [
      '<div class="top_teams"><h3>Top Teams</h3></div>',
      '<table class="teams-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Team:</span>',
          '</th>',
          '<th>',
            '<span id="last_team_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join(""),
  top_players_template:
    [
      '<div class="top_players"><h3>Top Players</h3></div>',
      '<table class="players-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Players:</span>',
          '</th>',
          '<th>',
            '<span id="last_player_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join("")
};

how to display variable value in alert box?

Clean way with no jQuery:

function check(some_id) {
    var content = document.getElementById(some_id).childNodes[0].nodeValue;
    alert(content);
}

This is assuming each span has only the value as a child and no embedded HTML.

What is an .inc and why use it?

It has no meaning, it is just a file extension. It is some people's convention to name files with a .inc extension if that file is designed to be included by other PHP files, but it is only convention.

It does have a possible disadvantage which is that servers normally are not configured to parse .inc files as php, so if the file sits in your web root and your server is configured in the default way, a user could view your php source code in the .inc file by visiting the URL directly.

Its only possible advantage is that it is easy to identify which files are used as includes. Although simply giving them a .php extension and placing them in an includes folder has the same effect without the disadvantage mentioned above.

How to fix .pch file missing on build?

  1. Right click to the project and select the property menu item
  2. goto C/C++ -> Precompiled Headers
  3. Select Not Using Precompiled Headers

How to pick just one item from a generator?

Generator is a function that produces an iterator. Therefore, once you have iterator instance, use next() to fetch the next item from the iterator. As an example, use next() function to fetch the first item, and later use for in to process remaining items:

# create new instance of iterator by calling a generator function
items = generator_function()

# fetch and print first item
first = next(items)
print('first item:', first)

# process remaining items:
for item in items:
    print('next item:', item)

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Optional Parameters in Web Api Attribute Routing

Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-

When we mark a parameter as optional in the action uri using ? character then we must provide default values to the parameters in the method signature as shown below:

MyMethod(string name = "someDefaultValue", int? Id = null)

How to Install Font Awesome in Laravel Mix

npm install font-awesome --save

add ~/ before path

@import "~/font-awesome/scss/font-awesome.scss";

mongod command not recognized when trying to connect to a mongodb server

Apart from having a Path variable, the directory C:\data\db is mandatory.

Create this and the error shall be solved.

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

.android  

check this folder in

C:\Users\user

its have an issue and fix it then restart android studio.

Is there a standard sign function (signum, sgn) in C/C++?

Bit off-topic, but I use this:

template<typename T>
constexpr int sgn(const T &a, const T &b) noexcept{
    return (a > b) - (a < b);
}

template<typename T>
constexpr int sgn(const T &a) noexcept{
    return sgn(a, T(0));
}

and I found first function - the one with two arguments, to be much more useful from "standard" sgn(), because it is most often used in code like this:

int comp(unsigned a, unsigned b){
   return sgn( int(a) - int(b) );
}

vs.

int comp(unsigned a, unsigned b){
   return sgn(a, b);
}

there is no cast for unsigned types and no additional minus.

in fact i have this piece of code using sgn()

template <class T>
int comp(const T &a, const T &b){
    log__("all");
    if (a < b)
        return -1;

    if (a > b)
        return +1;

    return 0;
}

inline int comp(int const a, int const b){
    log__("int");
    return a - b;
}

inline int comp(long int const a, long int const b){
    log__("long");
    return sgn(a, b);
}

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info:

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

Pass a javascript variable value into input type hidden value

You could do that like this:

<script type="text/javascript">
     function product(a,b)
     {
     return a*b;
     }
    document.getElementById('myvalue').value = product(a,b);
 </script>

 <input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">

How to build splash screen in windows forms application?

First you should create a form with or without Border (border-less is preferred for these things)

public class SplashForm : Form
{
    Form _Parent;
    BackgroundWorker worker;
    public SplashForm(Form parent)
    {
         InitializeComponent();
         BackgroundWorker worker = new BackgroundWorker();
         this.worker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.worker _DoWork);
         backgroundWorker1.RunWorkerAsync();
         _Parent = parent;
    }
    private void worker _DoWork(object sender, DoWorkEventArgs e)
    {
         Thread.sleep(500);
         this.hide();
         _Parent.show();
    }     
}

At Main you should use that

   static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new SplashForm());
            }
        }

'dependencies.dependency.version' is missing error, but version is managed in parent

I had the same problem and I rename the "repository" folder on ".m2" (something like repositoryBkp the name is not important is just in case something goes wrong) and create a new "repository" folder, then I re run maven and all the project compile successfully

Spring Security exclude url patterns in security annotation configurartion

When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):

@Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/authFailure").permitAll()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()

If you are still not having any joy, then you will need to provide more details/stacktrace etc.

Details of XML to Java config switch is here

Getting Java version at runtime

These articles seem to suggest that checking for 1.5 or 1.6 prefix should work, as it follows proper version naming convention.

Sun Technical Articles

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

How do I declare a two dimensional array?

You can also create an associative array, or a "hash-table" like array, by specifying the index of the array.

$array = array(
    0 => array(
        'name' => 'John Doe',
        'email' => '[email protected]'
    ),
    1 => array(
        'name' => 'Jane Doe',
        'email' => '[email protected]'
    ),
);

Which is equivalent to

$array = array();

$array[0] = array();
$array[0]['name'] = 'John Doe';
$array[0]['email'] = '[email protected]';

$array[1] = array();
$array[1]['name'] = 'Jane Doe';
$array[1]['email'] = '[email protected]';

form action with javascript

A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.

The best is to just set form action to your PHP script; if you need to do anything before submission you can just add to onsubmit

Edit turned out you didn't need any extra function, just a small change here:

function validateFormOnSubmit(theForm) {
    var reason = "";
    reason += validateName(theForm.name);
    reason += validatePhone(theForm.phone);
    reason += validateEmail(theForm.emaile);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
    } else {
        simpleCart.checkout();
    }
    return false;
}

Then in your form:

<form action="#" onsubmit="return validateFormOnSubmit(this);">

How do I perform a Perl substitution on a string while keeping the original?

If you write Perl with use strict;, then you'll find that the one line syntax isn't valid, even when declared.

With:

my ($newstring = $oldstring) =~ s/foo/bar/;

You get:

Can't declare scalar assignment in "my" at script.pl line 7, near ") =~"
Execution of script.pl aborted due to compilation errors.

Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with use strict;. For me, using use strict; is just a habit now. I do it automatically. Everyone should.

#!/usr/bin/env perl -wT

use strict;

my $oldstring = "foo one foo two foo three";
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

print "$oldstring","\n";
print "$newstring","\n";

How to Resize image in Swift?

You can use this for fit image at Swift 3;

extension UIImage {
    func resizedImage(newSize: CGSize) -> UIImage {
        // Guard newSize is different
        guard self.size != newSize else { return self }

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }

    func resizedImageWithinRect(rectSize: CGSize) -> UIImage {
        let widthFactor = size.width / rectSize.width
        let heightFactor = size.height / rectSize.height

        var resizeFactor = widthFactor
        if size.height > size.width {
            resizeFactor = heightFactor
        }

        let newSize = CGSize(width: size.width/resizeFactor, height: size.height/resizeFactor)
        let resized = resizedImage(newSize: newSize)
        return resized
    }
}

Usage;

let resizedImage = image.resizedImageWithinRect(rectSize: CGSize(width: 1900, height: 1900))

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

UIScrollView Scrollable Content Size Ambiguity

Xcode 11+, Swift 5.

According to @WantToKnow answer, I solved my issue, I prepared video and code

How do I get the current absolute URL in Ruby on Rails?

Rails 4

Controller:

def absolute_url
  request.base_url + request.original_fullpath
end

Action Mailer Notable changes in 4.2 release:

link_to and url_for generate absolute URLs by default in templates, it is no longer needed to pass only_path: false. (Commit)

View:

If you use the _url suffix, the generated URL is absolute. Use _path to get a relative URL.

<%= link_to "Home", root_url %>

For More Details, go to:

http://blog.grepruby.com/2015/04/absolute-url-full-url-in-rails-4.html

Date constructor returns NaN in IE, but works in Firefox and Chrome

I always store my date in UTC time.

This is my own function made from the different functions I found in this page.

It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.

This function return a timestamp.

The DATETIME is considered as a UTC date. Be carefull : If you expect a local datetime, this function is not for you.

    function datetimeToTimestamp(datetime)
    {
        var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
        if(regDatetime.test(datetime) === false)
            throw("Wrong format for the param. `Y-m-d H:i:s` expected.");

        var a=datetime.split(" ");
        var d=a[0].split("-");
        var t=a[1].split(":");

        var date = new Date();
        date.setUTCFullYear(d[0],(d[1]-1),d[2]);
        date.setUTCHours(t[0],t[1],t[2], 0);

        return date.getTime();
    }

How to get the row number from a datatable?

int index = dt.Rows.IndexOf(row);

But you're probably better off using a for loop instead of foreach.

Start an Activity with a parameter

The existing answers (pass the data in the Intent passed to startActivity()) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent which launches the Activity.

You can create a base-class Activity that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:

class BaseActivity extends Activity
{
    public BaseActivity(String param)
    {
        // Do something with param
    }
}

class DerivedActivity extends BaseActivity
{
    public DerivedActivity()
    {
        super("parameter");
    }
}

If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.

Python - Check If Word Is In A String

If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:

def smart_find(haystack, needle):
    if haystack.startswith(needle+" "):
        return True
    if haystack.endswith(" "+needle):
        return True
    if haystack.find(" "+needle+" ") != -1:
        return True
    return False

This assumes that commas and other punctuations have already been stripped out.

Variable not accessible when initialized outside function

A global variable would be best expressed in an external JavaScript file:

var system_status;

Make sure that this has not been used anywhere else. Then to access the variable on your page, just reference it as such. Say, for example, you wanted to fill in the results on a textbox,

document.getElementById("textbox1").value = system_status;

To ensure that the object exists, use the document ready feature of jQuery.

Example:

$(function() {
    $("#textbox1")[0].value = system_status;
});

Create instance of generic type in Java?

From Java Tutorial - Restrictions on Generics:

Cannot Create Instances of Type Parameters

You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:

public static <E> void append(List<E> list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}

As a workaround, you can create an object of a type parameter through reflection:

public static <E> void append(List<E> list, Class<E> cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}

You can invoke the append method as follows:

List<String> ls = new ArrayList<>();
append(ls, String.class);

Overflow:hidden dots at the end

You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.

Here's a demo on jsbin.

_x000D_
_x000D_
.cut-text { 
  text-overflow: ellipsis;
  overflow: hidden; 
  width: 160px; 
  height: 1.2em; 
  white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
_x000D_
_x000D_

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

If Else If In a Sql Server Function

ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
    RETURNS nvarchar(3)
AS BEGIN 

    DECLARE @Final nvarchar(3)
    SELECT @Final = CASE 
        WHEN yes_ans > no_ans  AND yes_ans > na_ans THEN 'Yes'
        WHEN no_ans  > yes_ans AND no_ans  > na_ans THEN 'No'
        WHEN na_ans  > yes_ans AND na_ans  > no_ans THEN 'N/A' END
    FROM dbo.qrc_maintally
    WHERE school_id = @SchoolId

Return @Final
End

As you can see, this simplifies the code a lot. It also makes other errors in your code more obvious: you're returning an nvarchar, but declared the function to return an int (corrected in the code above).

JQuery .hasClass for multiple values in an if statement

This is in case you need both classes present. For either or logic just use ||

$('el').hasClass('first-class') || $('el').hasClass('second-class')

Feel free to optimize as needed

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Get list of certificates from the certificate store in C#

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

Fluid width with equally spaced DIVs

Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between property fails (see the end of the post)

To date, the only clean solution for this is with the

CSS Grid Layout Module (Codepen demo)

Basically the relevant code necessary boils down to this:

ul {
  display: grid; /* (1) */
  grid-template-columns: repeat(auto-fit, 120px); /* (2) */
  grid-gap: 1rem; /* (3) */
  justify-content: space-between; /* (4) */
  align-content: flex-start; /* (5) */
}

1) Make the container element a grid container

2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit (as apposed to auto-fill) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).

3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

4) and 5) - Similar to flexbox.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(auto-fit, 120px);_x000D_
  grid-gap: 1rem;_x000D_
  justify-content: space-between;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  /* boring properties: */_x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  height: 120px;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen demo (Resize to see the effect)


Browser Support - Caniuse

Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)


NB:

Flexbox's space-between property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap) - fails, because you have no control over the alignment of the last row of items; the last row will always be justified (usually not what you want)

To demonstrate:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  _x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-wrap: wrap;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
  _x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  width: 110px;_x000D_
  height: 80px;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen (Resize to see what i'm talking about)


Further reading on CSS grids:

How to trigger a phone call when clicking a link in a web page on mobile phone

Essentially, use an <a> element with an href attr pointing to the phone number prefixed by tel:. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.

MDN Web Docs

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link

The HTML <a> element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

[…]

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

<a href="tel:+491570156">+49 157 0156</a>

IETF Documents

https://tools.ietf.org/html/rfc3966

The tel URI for Telephone Numbers

The "tel" URI has the following syntax:

telephone-uri = "tel:" telephone-subscriber

[…]

Examples

tel:+1-201-555-0123: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.

tel:7042;phone-context=example.com: The URI describes a local phone number valid within the context "example.com".

tel:863-1234;phone-context=+1-914-555: The URI describes a local phone number that is valid within a particular phone prefix.

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

Casting objects in Java

Sometimes you will like to receive as argument a Parent reference and inside you probably want to do something specific of a child.

abstract class Animal{
 public abstract void move();
}
class Shark extends Animal{
 public void move(){
  swim();
 }
 public void swim(){}
 public void bite(){}
}
class Dog extends Animal{
 public void move(){
  run();
 }
 public void run(){}
 public void bark(){}
}

...

void somethingSpecific(Animal animal){
 // Here you don't know and may don't care which animal enters
 animal.move(); // You can call parent methods but you can't call bark or bite.
 if(animal instanceof Shark){
  Shark shark = (Shark)animal;
  shark.bite(); // Now you can call bite!
 }
 //doSomethingSharky(animal); // You cannot call this method.
}

...

In above's method you can pass either Shark or Dog, but what if you have something like this:

void doSomethingSharky(Shark shark){
 //Here you cannot receive an Animal reference
}

That method can only be called by passing shark references So if you have an Animal (and it is deeply a Shark) you can call it like this:

Animal animal...
doSomethingSharky((Shark) animal)

Bottom line, you can use Parent references and it is usually better when you don't care about the implementation of the parent and use casting to use the Child as an specific object, it will be exactly the same object, but your reference know it, if you don't cast it, your reference will point to the same object but cannot be sure what kind of Animal would it be, therefore will only allow you to call known methods.

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

How to delete Project from Google Developers Console

  1. Go to the developers console and pick the application from the dropdown
  2. Select the utilities icon (see image below) and click project settings
  3. Click on the the Delete Project link
  4. Enter the project ID and click Shutdown, project will be deleted in 7 days

enter image description here

How to remove leading whitespace from each line in a file

Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt

Make column fixed position in bootstrap

Following the solution here http://jsfiddle.net/dRbe4/,

<div class="row">
    <div class="col-lg-3 fixed">
        Fixed content
    </div>
    <div class="col-lg-9 scrollit">
        Normal scrollable content
    </div>

 </div>

I modified some css to work just perfect:

.fixed {
        position: fixed;
        width: 25%;
}
.scrollit {
        float: left;
        width: 71%
}

Thanks @Lowkase for sharing the solution.

Private class declaration

You can.

package test;

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

class B {
  // Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

Looking for a 'cmake clean' command to clear up CMake output

To simplify cleaning when using "out of source" build (i.e. you build in the build directory), I use the following script:

$ cat ~/bin/cmake-clean-build
#!/bin/bash

if [ -d ../build ]; then
    cd ..
    rm -rf build
    mkdir build
    cd build
else
    echo "build directory DOES NOT exist"
fi

Every time you need to clean up, you should source this script from the build directory:

. cmake-clean-build

Scroll Element into View with Selenium

Here is how I do it with PHP webDriver for Selenium. It Works for Selenium stand-alone server 2.39.0 + https://github.com/Element-34/php-webdriver + Firefox 25.0

$element=$session->welement("xpath", "//input[@value='my val']");
$element->click();
$element=$session->welement("xpath", "//input[@value='ma val2']");
$element->location_in_view(); // < -- this is the candy
$element->click();

Note: I use a customized version of the Element34 PHP-webdriver. But there is not any change in the core. I just use my "welement" instead of "element". But it makes no influence on the case in question. The driver author says "to allow almost all API calls to be a direct transformation of what is defined in the WebDriver protocol itself." So you should have no problem with other programming languages.

Just clicking will not work in my setup. It will do a scroll instead of click, so I had to click twice without calling "location_in_view()".

Note: This method works for elements that can be viewed, like an input of type button.

Take a look at: http://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location

The description for JsonWireProtocol# suggest usage of location + moveto, because location _in_view is an internal method.

How to generate XML file dynamically using PHP?

Take a look at the Tiny But Strong templating system. It's generally used for templating HTML but there's an extension that works with XML files. I use this extensively for creating reports where I can have one code file and two template files - htm and xml - and the user can then choose whether to send a report to screen or spreadsheet.

Another advantage is you don't have to code the xml from scratch, in some cases I've been wanting to export very large complex spreadsheets, and instead of having to code all the export all that is required is to save an existing spreadsheet in xml and substitute in code tags where data output is required. It's a quick and a very efficient way to work.

Android: How to get a custom View's height and width?

Just got a solution to get height and width of a custom view:

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
    super.onSizeChanged(xNew, yNew, xOld, yOld);

    viewWidth = xNew;
    viewHeight = yNew;
}

Its working in my case.

Convert JsonObject to String

JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;

Undo scaffolding in Rails

First, if you have already run the migrations generated by the scaffold command, you have to perform a rollback first.

rake db:rollback

You can create scaffolding using:

rails generate scaffold MyFoo 

(or similar), and you can destroy/undo it using

rails destroy scaffold MyFoo

That will delete all the files created by generate, but not any additional changes you may have made manually.

How do android screen coordinates work?

enter image description here

This image presents both orientation(Landscape/Portrait)

To get MaxX and MaxY, read on.

For Android device screen coordinates, below concept will work.

Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x; 
int maxY = mdispSize.y;

EDIT:- ** **for devices supporting android api level older than 13. Can use below code.

    Display mdisp = getWindowManager().getDefaultDisplay();
    int maxX= mdisp.getWidth();
    int maxY= mdisp.getHeight();

(x,y) :-

1) (0,0) is top left corner.

2) (maxX,0) is top right corner

3) (0,maxY) is bottom left corner

4) (maxX,maxY) is bottom right corner

here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.

Why does npm install say I have unmet dependencies?

I believe it is because the dependency resolution is a bit broken, see https://github.com/npm/npm/issues/1341#issuecomment-20634338

Following are the possible solution :

  1. Manually need to install the top-level modules, containing unmet dependencies: npm install [email protected]

  2. Re-structure your package.json. Place all the high-level modules (serves as a dependency for others modules) at the bottom.

  3. Re-run the npm install command.

The problem could be caused by npm's failure to download all the package due to timed-out or something else.

Note: You can also install the failed packages manually as well using npm install [email protected].

Before running npm install, performing the following steps may help:

  • remove node_modules using rm -rf node_modules/
  • run npm cache clean

Why 'removing node_modules' sometimes is necessary? When a nested module fails to install during npm install, subsequent npm install won't detect those missing nested dependencies.

If that's the case, sometimes it's sufficient to remove the top-level dependency of those missing nested modules, and running npm install again. See

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

MAMP mysql server won't start. No mysql processes are running

The easiest solution: quit MAMP and remove the log files from MAMP/db/mysql directory [ib_logfile0, ib_logfile1] and restart MAMP. For more visit http://juanfra.me/2013/01/mysql-not-starting-mamp-fix/

How do you use the "WITH" clause in MySQL?

Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs). So it will be possible to write queries like this:


WITH RECURSIVE my_cte AS
(
  SELECT 1 AS n
  UNION ALL
  SELECT 1+n FROM my_cte WHERE n<10
)
SELECT * FROM my_cte;
+------+
| n    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
10 rows in set (0,00 sec)

How can I use onItemSelected in Android?

For Kotlin and bindings the code is:

binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            }
        }

Convert HTML string to image

       <!--ForExport data in iamge -->
        <script type="text/javascript">
            function ConvertToImage(btnExport) {
                html2canvas($("#dvTable")[0]).then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=hfImageData]").val(base64);
                    __doPostBack(btnExport.name, "");
                });
                return false;
            }
        </script>

        <!--ForExport data in iamge -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="../js/html2canvas.min.js"></script> 





<table>
                <tr>
                    <td valign="top">
                        <asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
                            OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
                        <div id="dvTable" class="divsection2" style="width: 350px">
                            <asp:HiddenField ID="hfImageData" runat="server" />
                            <table width="100%">
                                <tr>
                                    <td>
                                        <br />

                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
                                    </td>
                                </tr>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>


         protected void ExportToImage(object sender, EventArgs e)
                {
                    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
                    byte[] bytes = Convert.FromBase64String(base64);
                    Response.Clear();
                    Response.ContentType = "image/png";
                    Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();

                }

How to keep a git branch in sync with master

You are thinking in the right direction. Merge master with mobiledevicesupport continuously and merge mobiledevicesupport with master when mobiledevicesupport is stable. Each developer will have his own branch and can merge to and from either on master or mobiledevicesupport depending on their role.

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

How to get previous month and year relative to today, using strtotime and date?

if i understand the question correctly you just want last month and the year it is in:

<?php

  $month = date('m');
  $year = date('Y');
  $last_month = $month-1%12;
  echo ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month);

?>

Here is the example: http://codepad.org/c99nVKG8

window.close and self.close do not close the window in Chrome

I found a new way that works for me perfetly

var win = window.open("about:blank", "_self");
win.close();

Convert integer to binary in C#

    static void convertToBinary(int n)
    {
        Stack<int> stack = new Stack<int>();
        stack.Push(n);
        // step 1 : Push the element on the stack
        while (n > 1)
        {
            n = n / 2;
            stack.Push(n);
        }

        // step 2 : Pop the element and print the value
        foreach(var val in stack)
        {
            Console.Write(val % 2);
        }
     }

Android open camera from button

You can create a camera intent and call it as startActivityForResult(intent).

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

   // start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

Is it possible to use an input value attribute as a CSS selector?

In Chrome 72 (2019-02-09) I've discovered that the :in-range attribute is applied to empty date inputs, for some reason!

So this works for me: (I added the :not([max]):not([min]) selectors to avoid breaking date inputs that do have a range applied to them:

input[type=date]:not([max]):not([min]):in-range {
    color: blue;
}

Screenshot:


enter image description here


Here's a runnable sample:

_x000D_
_x000D_
window.addEventListener( 'DOMContentLoaded', onLoad );_x000D_
_x000D_
function onLoad() {_x000D_
    _x000D_
    document.getElementById( 'date4' ).value = "2019-02-09";_x000D_
    _x000D_
    document.getElementById( 'date5' ).value = null;_x000D_
    _x000D_
}
_x000D_
label {_x000D_
    display: block;_x000D_
    margin: 1em;_x000D_
}_x000D_
_x000D_
input[type=date]:not([max]):not([min]):in-range {_x000D_
    color: blue;_x000D_
}
_x000D_
<label>_x000D_
    <input type="date" id="date1" />_x000D_
    Without HTML value=""_x000D_
</label>_x000D_
    _x000D_
<label>_x000D_
    <input type="date" id="date2" value="2019-02-09" />_x000D_
    With HTML value=""_x000D_
</label>_x000D_
_x000D_
<label>_x000D_
    <input type="date" id="date3" />_x000D_
    Without HTML value="" but modified by user_x000D_
</label>_x000D_
    _x000D_
<label>_x000D_
    <input type="date" id="date4" />_x000D_
    Without HTML value="" but set by script_x000D_
</label>_x000D_
    _x000D_
<label>_x000D_
    <input type="date" id="date5" value="2019-02-09" />_x000D_
    With HTML value="" but cleared by script_x000D_
</label>
_x000D_
_x000D_
_x000D_

Arrays in unix shell?

In ksh you do it:

set -A array element1 element2 elementn

# view the first element
echo ${array[0]}

# Amount elements (You have to substitute 1)
echo ${#array[*]}

# show last element
echo ${array[ $(( ${#array[*]} - 1 )) ]}

Using Bootstrap Tooltip with AngularJS

You can use selector option for dynamic single page applications:

jQuery(function($) {
    $(document).tooltip({
        selector: '[data-toggle="tooltip"]'
    });
});

if a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added.

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

i was facing the same problem for a get method i was returning an "int" for the @get method Strangely when i change the return type to String the error was gone.Give it a try and if someone knows the logic behind it kindly share it

C# 4.0: Convert pdf to byte[] and vice versa

// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

Postgres password authentication fails

pg_hba.conf entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf in order to get proper help.

Change this line:

host    all             all             <my-ip-address>/32        md5

To reflect your local network settings. So, if your IP is 192.168.16.78 (class C) with a mask of 255.255.255.0, then put this:

host    all             all             192.168.16.0/24        md5

Make sure your WINDOWS MACHINE is in that network 192.168.16.0 and try again.

How to synchronize or lock upon variables in Java?

For this functionality you are better off not using a lock at all. Try an AtomicReference.

public class Sample {
    private final AtomicReference<String> msg = new AtomicReference<String>();

    public void setMsg(String x) {
        msg.set(x);
    }

    public String getMsg() {
        return msg.getAndSet(null);
    }
}

No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.

How to launch an EXE from Web page (asp.net)

Did you try a UNC share?

\\server\share\foo.exe

MySQL update CASE WHEN/THEN/ELSE

That's because you missed ELSE.

"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)

How do you remove the title text from the Android ActionBar?

as a workaround just add this line incase you have custom action/toolbars

this.setTitle("");

in your Activity

Path to Powershell.exe (v 2.0)

I think $PsHome has the information you're after?

PS .> $PsHome
C:\Windows\System32\WindowsPowerShell\v1.0

PS .> Get-Help about_automatic_variables

TOPIC
    about_Automatic_Variables ...

How to use XMLReader in PHP?

This Works Better and Faster For Me


<html>
<head>
<script>
function showRSS(str) {
  if (str.length==0) {
    document.getElementById("rssOutput").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("rssOutput").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","getrss.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
<option value="job">Job</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html> 

**The Backend File **


<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected
if($q=="Google") {
  $xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
} elseif($q=="ZDN") {
  $xml=("https://www.zdnet.com/news/rss.xml");
}elseif($q == "job"){
  $xml=("https://ngcareers.com/feed");
}

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"
echo("<p><a href='" . $channel_link
  . "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");

//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');

$count = $x->length;

// print_r( $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue);
// return;

for ($i=0; $i <= $count; $i++) {
  //Title
  $item_title = $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue;
  //Link
  $item_link = $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue;
  //Description
  $item_desc = $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue;
  //Category
  $item_cat = $x->item(0)->getElementsByTagName('category')->item(0)->nodeValue;


  echo ("<p>Title: <a href='" . $item_link
  . "'>" . $item_title . "</a>");
  echo ("<br>");
  echo ("Desc: ".$item_desc);
   echo ("<br>");
  echo ("Category: ".$item_cat . "</p>");
}
?> 

How to check type of files without extensions in python?

There are Python libraries that can recognize files based on their content (usually a header / magic number) and that don't rely on the file name or extension.

If you're addressing many different file types, you can use python-magic. That's just a Python binding for the well-established magic library. This has a good reputation and (small endorsement) in the limited use I've made of it, it has been solid.

There are also libraries for more specialized file types. For example, the Python standard library has the imghdr module that does the same thing just for image file types.

If you need dependency-free (pure Python) file type checking, see filetype.

SQL, How to convert VARCHAR to bigint?

an alternative would be to do something like:

SELECT
   CAST(P0.seconds as bigint) as seconds
FROM
   (
   SELECT
      seconds
   FROM
      TableName
   WHERE
      ISNUMERIC(seconds) = 1
   ) P0

Javascript - removing undefined fields from an object

A one-liner using ES6 arrow function and ternary operator:

Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : {});

Or use short-circuit evaluation instead of ternary: (@Matt Langlois, thanks for the info!)

Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])

Same example using if statement:

Object.keys(obj).forEach(key => {
  if (obj[key] === undefined) {
    delete obj[key];
  }
});

If you want to remove the items from nested objects as well, you can use a recursive function:

const removeEmpty = (obj) => {
  let newObj = {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
    else if (obj[key] !== undefined) newObj[key] = obj[key];
  });
  return newObj;
};

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.


Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

Installing PHP Zip Extension

I tried changing the repository list with:

http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe

But none of them seem to work, but I finally found a repository that works running the following command

add-apt-repository ppa:ondrej/php

And then updating and installing normally the package using apt-get

As you can see it's installed at last.

No process is on the other end of the pipe (SQL Server 2012)

So, I had this recently also, for integrated security, It turns out that my issue was actually fairly simple to fix but mainly because I had forgotten to add "Trusted_Connection=True" to my connection string.

I know that may seem fairly obvious but it had me going for 20 minutes or so until I realised that I had copied my connection string format from connectionstrings.com and that portion of the connection string was missing.

Simple and I feel a bit daft, but it was the answer for me.

Setting ANDROID_HOME enviromental variable on Mac OS X

Setup ANDROID_HOME , JAVA_HOME enviromental variable on Mac OS X

Add In .bash_profile file

export JAVA_HOME=$(/usr/libexec/java_home)

export ANDROID_HOME=/Users/$USER/Library/Android/sdk

export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

For Test

echo $ANDROID_HOME
echo $JAVA_HOME

How to pass arguments from command line to gradle

It's possible to utilize custom command line options in Gradle to end up with something like:

./gradlew printPet --pet="puppies!"

However, custom command line options in Gradle are an incubating feature.

Java solution

To end up with something like this follow the instructions here:

import org.gradle.api.tasks.options.Option;

public class PrintPet extends DefaultTask {
    private String pet;

    @Option(option = "pet", description = "Name of the cute pet you would like to print out!")
    public void setPet(String pet) {
        this.pet = pet;
    }

    @Input
    public String getPet() {
        return pet;
    }

    @TaskAction
    public void print() {
        getLogger().quiet("'{}' are awesome!", pet);
    }
}

Then register it:

task printPet(type: PrintPet)

Now you can do:

./gradlew printPet --pet="puppies"

output:

Puppies! are awesome!

Kotlin solution

open class PrintPet : DefaultTask() {

    @Suppress("UnstableApiUsage")
    @set:Option(option = "pet", description = "The cute pet you would like to print out")
    @get:Input
    var pet: String = ""

    @TaskAction
    fun print() {    
        println("$pet are awesome!")
    }
}

then register the task with:

tasks.register<PrintPet>("printPet")

PHP function overloading

Sadly there is no overload in PHP as it is done in C#. But i have a little trick. I declare arguments with default null values and check them in a function. That way my function can do different things depending on arguments. Below is simple example:

public function query($queryString, $class = null) //second arg. is optional
{
    $query = $this->dbLink->prepare($queryString);
    $query->execute();

    //if there is second argument method does different thing
    if (!is_null($class)) { 
        $query->setFetchMode(PDO::FETCH_CLASS, $class);
    }

    return $query->fetchAll();
}

//This loads rows in to array of class
$Result = $this->query($queryString, "SomeClass");
//This loads rows as standard arrays
$Result = $this->query($queryString);

Links in <select> dropdown options

You can use this code:

<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
    <option value="URL">Book</option>
    <option value="URL">Pen</option>
    <option value="URL">Read</option>
    <option value="URL">Apple</option>
</select>

Disabling enter key for form

if you use jQuery, its quite simple. Here you go

$(document).keypress(
  function(event){
    if (event.which == '13') {
      event.preventDefault();
    }
});

Read/Write String from/to a File in Android

For those looking for a general strategy for reading and writing a string to file:

First, get a file object

You'll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

Or with Google Guava

String contents = Files.toString(file, StandardCharsets.UTF_8);

Read the file to a string

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

Or if you are using Google Guava

String contents = Files.toString(file,"UTF-8");

For completeness I'll mention

String contents = new Scanner(file).useDelimiter("\\A").next();

which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).

Notes

For each of these strategies, you'll be asked to catch an IOException.

The default character encoding on Android is UTF-8.

If you are using external storage, you'll need to add to your manifest either:

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

or

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

Write permission implies read permission, so you don't need both.

Getting index value on razor foreach

In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:

 @foreach (var item in Model)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtCadastro)
                                </td>

                                <td style="width:50%">
                                    @Html.DisplayFor(modelItem => item.DsLembrete)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtLembrete)
                                </td>
                                <td>
                                    @{ 
                                        var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
                                    }
                                    <button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
                                    <button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
                                </td>
                                <td class="text-right">
                                    <button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
                                </td>
                            </tr>
                        }

do as coded:

@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}

and use it like this:

<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>

ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.

How to clear cache of Eclipse Indigo

you can use -clean parameter while starting eclipse like

C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

Is there a way to select sibling nodes?

var sibling = node.nextSibling;

This will return the sibling immediately after it, or null no more siblings are available. Likewise, you can use previousSibling.

[Edit] On second thought, this will not give the next div tag, but the whitespace after the node. Better seems to be

var sibling = node.nextElementSibling;

There also exists a previousElementSibling.

How do I write a correct micro-benchmark in Java?

I know this question has been marked as answered but I wanted to mention two libraries that help us to write micro benchmarks

Caliper from Google

Getting started tutorials

  1. http://codingjunkie.net/micro-benchmarking-with-caliper/
  2. http://vertexlabs.co.uk/blog/caliper

JMH from OpenJDK

Getting started tutorials

  1. Avoiding Benchmarking Pitfalls on the JVM
  2. Using JMH for Java Microbenchmarking
  3. Introduction to JMH

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

How to read and write excel file

Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.

Import data

try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
  rowStream
    // skip the header row that contains the column names
    .skip(1)
    .forEach(row -> {
      System.out.println(
        "row n°" + row.rowIndex()
        + " column 'User login' value : " + row.cell("User login").asString()
        + " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
      );
    });
}

Export data

Windmill
  .export(Arrays.asList(bean1, bean2, bean3))
  .withHeaderMapping(
    new ExportHeaderMapping<Bean>()
      .add("Name", Bean::getName)
      .add("User login", bean -> bean.getUser().getLogin())
  )
  .asExcel()
  .writeTo(new FileOutputStream("Export.xlsx"));

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I've been having this issue also for about 8-9 days. Here's some background: I'm developing a simple Java application that runs in bash.

Details:

  • Spring 2.5.6
  • Hibernate3.2.3.ga
  • With maven. (The base of the project is from mkyong.com , the spring tutorial without anotations )
  • MySQL version:
[jvazquez@archbox ~]$ mysql --version
mysql  Ver 14.14 Distrib 5.5.9, for Linux (i686) using readline 5.1
Linux archbox 2.6.37-ARCH #1 SMP PREEMPT Fri Feb 18 16:58:42 UTC 2011 i686 Intel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz GenuineIntel GNU/Linux

The application works fine in Arch Linux, Mac OS X 10.6, and FreeBSD 7.2. When I moved the jar file to another arch linux in a different host, using the same mysql, a similar my.cnf, and the similar kernel version, the connection died and obtained the same error as the original poster:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I tried every possible combination for this that I found on so and the forums (http://forums.mysql.com/read.php?39,180347,180347#msg-180347 for example, which is closed now and I can't post .. ), specifically:

  • Triple check that I wasn't using skip networking. (verified with ps aux and the my.cnf)
  • Tried enable log_warnings=1 in the my.cnf but obviously, I wasn't hitting the server so I didn't saw anything while using the app
  • SHOW ENGINE innodb STATUS didn't show anything at all; during the tests I could connect via shell, and php also connected to the mysql server
  • /etc/hosts has localhost 127.0.0.1
  • Tried the jdbc properties using localhost and 127.0.0.1 with no results
  • Tried adding c3p0 and changed the max_wait
  • Max connections in the my.cnf was changed to 900 , 2000 and still nothing my.cnf
  • Added wait_timeout = 60 my.cnf
  • Added net_wait_timeout = 360 my.cnf
  • Added the destroy-method="close" spring.xml

As it was pointed out (if you look up for the same exception , you will find several so threads about the issue Reproduce com.mysql.jdbc.exceptions.jdbc4.CommunicationsException with a setup of Spring, hibernate and C3P0 for example ).

  1. If you are using tomcat, please check the security exception (again, it is on SO, you will find it )
  2. Check that you can resolve that url that you are using
  3. Try adding c3p0.
  4. Verify that there isn't a firewall rejecting your connections
  5. Finally , if you are using GNU/Linux ( ARch linux for example and you indeed obtain this exception ) Try MySQL Forums :: JDBC and Java :: EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost

If the link get's removed, just add mysqld:ALL to /etc/hosts.allow

I know that is a bit extense, but it may help anybody using GNU/Linux and having this exception and this thread seemed the best place to post my research.

Hope it helps

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

That worked for me:

mysql --user=root mysql
CREATE USER 'some_user'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'some_user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;