Programs & Examples On #Uialertsheet

UIAlertSheet is a misrepresentation of UIActionSheet, a type of modal overlay view that presents the user with a set of possible actions to take.

How to get JSON from webpage into Python script

In Python 2, json.load() will work instead of json.loads()

import json
import urllib

url = 'https://api.github.com/users?since=100'
output = json.load(urllib.urlopen(url))
print(output)

Unfortunately, that doesn't work in Python 3. json.load is just a wrapper around json.loads that calls read() for a file-like object. json.loads requires a string object and the output of urllib.urlopen(url).read() is a bytes object. So one has to get the file encoding in order to make it work in Python 3.

In this example we query the headers for the encoding and fall back to utf-8 if we don't get one. The headers object is different between Python 2 and 3 so it has to be done different ways. Using requests would avoid all this, but sometimes you need to stick to the standard library.

import json
from six.moves.urllib.request import urlopen

DEFAULT_ENCODING = 'utf-8'
url = 'https://api.github.com/users?since=100'
urlResponse = urlopen(url)

if hasattr(urlResponse.headers, 'get_content_charset'):
    encoding = urlResponse.headers.get_content_charset(DEFAULT_ENCODING)
else:
    encoding = urlResponse.headers.getparam('charset') or DEFAULT_ENCODING

output = json.loads(urlResponse.read().decode(encoding))
print(output)

$.focus() not working

ADDITIONAL SOLUTION Had same issue where focus() didn't seem to work but eventually it turned out that what was needed was scrolling to the correct position:

Is there a "standard" format for command line/shell help text?

Microsoft has their own Command Line Standard specification:

This document is focused at developers of command line utilities. Collectively, our goal is to present a consistent, composable command line user experience. Achieving that allows a user to learn a core set of concepts (syntax, naming, behaviors, etc) and then be able to translate that knowledge into working with a large set of commands. Those commands should be able to output standardized streams of data in a standardized format to allow easy composition without the burden of parsing streams of output text. This document is written to be independent of any specific implementation of a shell, set of utilities or command creation technologies; however, Appendix J - Using Windows Powershell to implement the Microsoft Command Line Standard shows how using Windows PowerShell will provide implementation of many of these guidelines for free.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

Difference between natural join and inner join

  • An inner join is one where the matching row in the joined table is required for a row from the first table to be returned
  • An outer join is one where the matching row in the joined table is not required for a row from the first table to be returned
  • A natural join is a join (you can have either natural left or natural right) that assumes the join criteria to be where same-named columns in both table match

I would avoid using natural joins like the plague, because natural joins are:

  • not standard sql [SQL 92] and therefore not portable, not particularly readable (by most SQL coders) and possibly not supported by various tools/libraries
  • not informative; you can't tell what columns are being joined on without referring to the schema
  • your join conditions are invisibly vulnerable to schema changes - if there are multiple natural join columns and one such column is removed from a table, the query will still execute, but probably not correctly and this change in behaviour will be silent
  • hardly worth the effort; you're only saving about 10 seconds of typing

Why does my Eclipse keep not responding?

Try this, it worked for me!

If you happen to have Eclipse not responding anymore sometimes, the reason could be that you sit on a 64bit machine where eclipse needs more memory. Be sure to have (at least) the following configurations in your eclipse.ini (I even use bigger values for the PermSizes):

-Xms512m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m

Two inline-block, width 50% elements wrap to second line

It is because display:inline-block takes into account white-space in the html. If you remove the white-space between the div's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/

<div id="col1">content</div><div id="col2">content</div>

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

Docker: Multiple Dockerfiles in project

Use docker-compose and multiple Dockerfile in separate directories

Don't rename your Dockerfile to Dockerfile.db or Dockerfile.web, it may not be supported by your IDE and you will lose syntax highlighting.

As Kingsley Uchnor said, you can have multiple Dockerfile, one per directory, which represent something you want to build.

I like to have a docker folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.

docker-compose.yml
docker
+-- web
¦   +-- Dockerfile
+-- db
    +-- Dockerfile

docker-compose.yml example:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: ./docker/web
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  db:
    # will build ./docker/db/Dockerfile
    build: ./docker/db
    ports:
      - "3306:3306"
  redis:
    # will use docker hub's redis prebuilt image from here:
    # https://hub.docker.com/_/redis/
    image: "redis:alpine"

docker-compose command line usage example:

# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d

# get help
docker-compose --help

In case you need files from previous folders when building your Dockerfile

You can still use the above solution and place your Dockerfile in a directory such as docker/web/Dockerfile, all you need is to set the build context in your docker-compose.yml like this:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code

This way, you'll be able to have things like this:

config-on-root.ini
docker-compose.yml
docker
+-- web
    +-- Dockerfile
    +-- some-other-config.ini

and a ./docker/web/Dockerfile like this:

FROM alpine:latest

COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /

Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.

"CAUTION: provisional headers are shown" in Chrome debugger

This message can occur when the website is protected using HSTS. Then, when someone links to the HTTP version of the URL, the browser, as instructed by HSTS, does not issue an HTTP request, but internally redirects to the HTTPS resource securely. This is to avoid HTTPS downgrade attacks such as sslstrip.

Seeing the underlying SQL in the Spring JdbcTemplate?

This works for me with org.springframework.jdbc-3.0.6.RELEASE.jar. I could not find this anywhere in the Spring docs (maybe I'm just lazy) but I found (trial and error) that the TRACE level did the magic.

I'm using log4j-1.2.15 along with slf4j (1.6.4) and properties file to configure the log4j:

log4j.logger.org.springframework.jdbc.core = TRACE

This displays both the SQL statement and bound parameters like this:

Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown

Not sure about the SQL type unknown but I guess we can ignore it here

For just an SQL (i.e. if you're not interested in bound parameter values) DEBUG should be enough.

Mercurial: how to amend the last commit?

Recent versions of Mercurial include the evolve extension which provides the hg amend command. This allows amending a commit without losing the pre-amend history in your version control.

hg amend [OPTION]... [FILE]...

aliases: refresh

combine a changeset with updates and replace it with a new one

Commits a new changeset incorporating both the changes to the given files
and all the changes from the current parent changeset into the repository.

See 'hg commit' for details about committing changes.

If you don't specify -m, the parent's message will be reused.

Behind the scenes, Mercurial first commits the update as a regular child
of the current parent. Then it creates a new commit on the parent's
parents with the updated contents. Then it changes the working copy parent
to this new combined changeset. Finally, the old changeset and its update
are hidden from 'hg log' (unless you use --hidden with log).

See https://www.mercurial-scm.org/doc/evolution/user-guide.html#example-3-amend-a-changeset-with-evolve for a complete description of the evolve extension.

How to select only 1 row from oracle sql?

"FirstRow" Is a restriction and therefor it's place in the where clause not in the select clause. And it's called rownum

select * from dual where rownum = 1;

What is a magic number, and why is it bad?

A magic number is a direct usage of a number in the code.

For example, if you have (in Java):

public class Foo {
    public void setPassword(String password) {
         // don't do this
         if (password.length() > 7) {
              throw new InvalidArgumentException("password");
         }
    }
}

This should be refactored to:

public class Foo {
    public static final int MAX_PASSWORD_SIZE = 7;

    public void setPassword(String password) {
         if (password.length() > MAX_PASSWORD_SIZE) {
              throw new InvalidArgumentException("password");
         }
    }
}

It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.

The JDK is full of examples like in Integer, Character and Math classes.

PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.

Multi-dimensional arraylist or list in C#?

Depending on your exact requirements, you may do best with a jagged array of sorts with:

List<string>[] results = new { new List<string>(), new List<string>() };

Or you may do well with a list of lists or some other such construct.

phpexcel to download

Instead of saving it to a file, save it to php://output­Docs:

$objWriter->save('php://output');

This will send it AS-IS to the browser.

You want to add some headers­Docs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):

// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');

// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');

// Write file to the browser
$objWriter->save('php://output');

First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.

Move an array element from one array position to another

In your example, because is an array of string we can use a ranking object to reorder the string array:

let rank =  { 'a': 0, 'b': 1, 'c': 2, 'd': 0.5, 'e': 4 };
arr.sort( (i, j) => rank[i] - rank[j] );

We can use this approach to write a move function that works on a string array:

_x000D_
_x000D_
function stringArrayMove(arr, from, to)
{
  let rank = arr.reduce( (p, c, i) => ( p[c] = i, p ), ({ }) );
  // rank = { 'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4 }
  rank[arr[from]] = to - 0.5;
  // rank = { 'a': 0, 'b': 1, 'c': 2, 'd': 1.5, 'e': 4 }
  arr.sort( (i, j) => rank[i] - rank[j] );
  // arr = [ 'a', 'd', 'b', 'c', 'e' ];
}

let arr = [ 'a', 'b', 'c', 'd', 'e' ];
stringArrayMove(arr, 3, 1);
console.log( JSON.stringify(arr) );
_x000D_
_x000D_
_x000D_

If, however, the thing we wanted to sort is an array of object, we can introduce the ranking as a new property of each object, i.e.

let arr = [ { value: 'a', rank: 0 },
            { value: 'b', rank: 1 },
            { value: 'c', rank: 2 },
            { value: 'd', rank: 0.5 },
            { value: 'e', rank: 4 } ];
arr.sort( (i, j) => i['rank'] - j['rank'] );

We can use Symbol to hide the visibility of this property, i.e. it will not be shown in JSON.stringify. We can generalize this in an objectArrayMove function:

_x000D_
_x000D_
function objectArrayMove(arr, from, to) {
  let rank = Symbol("rank");
  arr.forEach( (item, i) => item[rank] = i );
  arr[from][rank] = to - 0.5;
  arr.sort( (i, j) => i[rank] - j[rank]);
}
let arr = [ { value: 'a' }, { value: 'b' }, { value: 'c' }, { value: 'd' }, { value: 'e' } ];
console.log( 'array before move: ', JSON.stringify( arr ) );
// array before move:  [{"value":"a"},{"value":"b"},{"value":"c"},{"value":"d"},{"value":"e"}]
objectArrayMove(arr, 3, 1);
console.log( 'array after move: ', JSON.stringify( arr ) );
// array after move:  [{"value":"a"},{"value":"d"},{"value":"b"},{"value":"c"},{"value":"e"}]
_x000D_
_x000D_
_x000D_

How to send a GET request from PHP?

http_get should do the trick. The advantages of http_get over file_get_contents include the ability to view HTTP headers, access request details, and control the connection timeout.

$response = http_get("http://www.example.com/file.xml");

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Best way to store password in database

I may be slightly off-topic as you did mention the need for a username and password, and my understanding of the issue is admitedly not the best but is OpenID something worth considering?

If you use OpenID then you don't end up storing any credentials at all if I understand the technology correctly and users can use credentials that they already have, avoiding the need to create a new identity that is specific to your application.

It may not be suitable if the application in question is purely for internal use though

RPX provides a nice easy way to intergrate OpenID support into an application.

Importing a CSV file into a sqlite3 database table using Python

You can do this using blaze & odo efficiently

import blaze as bz
csv_path = 'data.csv'
bz.odo(csv_path, 'sqlite:///data.db::data')

Odo will store the csv file to data.db (sqlite database) under the schema data

Or you use odo directly, without blaze. Either ways is fine. Read this documentation

How to extract img src, title and alt from html using php?

EDIT : now that I know better

Using regexp to solve this kind of problem is a bad idea and will likely lead in unmaintainable and unreliable code. Better use an HTML parser.

Solution With regexp

In that case it's better to split the process into two parts :

  • get all the img tag
  • extract their metadata

I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code :

/* preg_match_all match the regexp in all the $html string and output everything as 
an array in $result. "i" option is used to make it case insensitive */

preg_match_all('/<img[^>]+>/i',$html, $result); 

print_r($result);
Array
(
    [0] => Array
        (
            [0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />
            [1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
            [2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />
            [3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />
            [4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />

[...]
        )

)

Then we get all the img tag attributes with a loop :

$img = array();
foreach( $result as $img_tag)
{
    preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}

print_r($img);

Array
(
    [<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array
        (
            [0] => Array
                (
                    [0] => src="/Content/Img/stackoverflow-logo-250.png"
                    [1] => alt="logo link to homepage"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                )

            [2] => Array
                (
                    [0] => "/Content/Img/stackoverflow-logo-250.png"
                    [1] => "logo link to homepage"
                )

        )

    [<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array
        (
            [0] => Array
                (
                    [0] => src="/content/img/vote-arrow-up.png"
                    [1] => alt="vote up"
                    [2] => title="This was helpful (click again to undo)"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                    [2] => title
                )

            [2] => Array
                (
                    [0] => "/content/img/vote-arrow-up.png"
                    [1] => "vote up"
                    [2] => "This was helpful (click again to undo)"
                )

        )

    [<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array
        (
            [0] => Array
                (
                    [0] => src="/content/img/vote-arrow-down.png"
                    [1] => alt="vote down"
                    [2] => title="This was not helpful (click again to undo)"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                    [2] => title
                )

            [2] => Array
                (
                    [0] => "/content/img/vote-arrow-down.png"
                    [1] => "vote down"
                    [2] => "This was not helpful (click again to undo)"
                )

        )

    [<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array
        (
            [0] => Array
                (
                    [0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
                    [1] => alt="gravatar image"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                )

            [2] => Array
                (
                    [0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
                    [1] => "gravatar image"
                )

        )

   [..]
        )

)

Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using ob_start and loading / saving from a text file.

How does this stuff work ?

First, we use preg_ match_ all, a function that gets every string matching the pattern and ouput it in it's third parameter.

The regexps :

<img[^>]+>

We apply it on all html web pages. It can be read as every string that starts with "<img", contains non ">" char and ends with a >.

(alt|title|src)=("[^"]*")

We apply it successively on each img tag. It can be read as every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between ().

Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this online regexp tester.

EDIT : answer to the first comment.

It's true that I did not think about the (hopefully few) people using single quotes.

Well, if you use only ', just replace all the " by '.

If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"].

jquery: get id from class selector

Nothing from this examples , works for me

for (var i = 0; i < res.results.length; i++) {
        $('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}

    $('.dd-item').click(function () {
    console.log($(this).attr('id'));
    });

Create an empty object in JavaScript with {} or new Object()?

These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

It's important that your THEAD not be empty in table.As dataTable requires you to specify the number of columns of the expected data . As per your data it should be

<table id="datatable">
    <thead>
        <tr>
            <th>Subscriber ID</th>
            <th>Install Location</th>
            <th>Subscriber Name</th>
            <th>some data</th>
        </tr>
    </thead>
</table>

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

As of upgrading from pip 7.x.x to 8.x.x on Python 3.4 (for *.whl support).

Wrong command: pip install --upgrade pip (can't move pip.exe to temporary folder, permisson denied)

OK variant: py -3.4 -m pip install --upgrade pip (do not execute pip.exe)

How to print the full NumPy array, without truncation?

with np.printoptions(edgeitems=50):
    print(x)

Change 50 to how many lines you wanna see

Source: here

How to use sys.exit() in Python

In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:

so:

import sys

and when finished:

sys.exit()

How can I stop a While loop?

I would do it using a for loop as shown below :

def determine_period(universe_array):
    tmp = universe_array
    for period in xrange(1, 13):
        tmp = apply_rules(tmp)
        if numpy.array_equal(tmp, universe_array):
            return period
    return 0

MVC 4 Edit modal form using Bootstrap

In reply to Dimitrys answer but using Ajax.BeginForm the following works at least with MVC >5 (4 not tested).

  1. write a model as shown in the other answers,

  2. In the "parent view" you will probably use a table to show the data. Model should be an ienumerable. I assume, the model has an id-property. Howeverm below the template, a placeholder for the modal and corresponding javascript

    <table>
    @foreach (var item in Model)
    {
        <tr> <td id="[email protected]"> 
            @Html.Partial("dataRowView", item)
        </td> </tr>
    }
    </table>
    
    <div class="modal fade" id="editor-container" tabindex="-1" 
         role="dialog" aria-labelledby="editor-title">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" id="editor-content-container"></div>
        </div>
    </div> 
    
    <script type="text/javascript">
        $(function () {
            $('.editor-container').click(function () {
                var url = "/area/controller/MyEditAction";  
                var id = $(this).attr('data-id');  
                $.get(url + '/' + id, function (data) {
                    $('#editor-content-container').html(data);
                    $('#editor-container').modal('show');
                });
            });
        });
    
        function success(data,status,xhr) {
            $('#editor-container').modal('hide');
            $('#editor-content-container').html("");
        }
    
        function failure(xhr,status,error) {
            $('#editor-content-container').html(xhr.responseText);
            $('#editor-container').modal('show');
        }
    </script>
    

note the "editor-success-id" in data table rows.

  1. The dataRowView is a partial containing the presentation of an model's item.

    @model ModelView
    @{
        var item = Model;
    }
    <div class="row">
            // some data 
            <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
    </div>
    
  2. Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ... ).

    @model Model
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="editor-title">Title</h4>
    </div>
    @using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                        new AjaxOptions
                        {
                            InsertionMode = InsertionMode.Replace,
                            HttpMethod = "POST",
                            UpdateTargetId = "editor-success-" + @Model.Id,
                            OnSuccess = "success",
                            OnFailure = "failure",
                        }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.Id)
        <div class="modal-body">
            <div class="form-horizontal">
                // Models input fields
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    }
    

This is where magic happens: in AjaxOptions, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.

This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.

But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:

  1. the corresponding controller action method for the partial edit modal

    [HttpGet]
    public async Task<ActionResult> EditPartData(Guid? id)
    {
        // Find the data row and return the edit form
        Model input = await db.Models.FindAsync(id);
        return PartialView("EditModel", input);
    }
    
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> MyEditAction([Bind(Include =
       "Id,Fields,...")] ModelView input)
    {
        if (TryValidateModel(input))
        {  
            // save changes, return new data row  
            // status code is something in 200-range
            db.Entry(input).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return PartialView("dataRowView", (ModelView)input);
        }
    
        // set the "error status code" that will redisplay the modal
        Response.StatusCode = 400;
        // and return the edit form, that will be displayed as a 
        // modal again - including the modelstate errors!
        return PartialView("EditModel", (Model)input);
    }
    

This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.

Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js (may be installed by NuGet):

        bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                    "~/Scripts/jquery.unobtrusive-ajax.js"));

How can I easily switch between PHP versions on Mac OSX?

i think unlink & link php versions are not enough because we are often using php with apache(httpd), so need to update httpd.conf after switch php version.

i have write shell script for disable/enable php_module automatically inside httpd.conf, look at line 46 to line 54 https://github.com/dangquangthai/switch-php-version-on-mac-sierra/blob/master/switch-php#L46

Follow my steps:

1) Check installed php versions by brew, for sure everything good

> brew list | grep php
#output
php56
php56-intl
php56-mcrypt
php71
php71-intl
php71-mcrypt

2) Run script

> switch-php 71 # or switch-php 56
#output
PHP version [71] found
Switching from [php56] to [php71] ... 
Unlink php56 ... [OK] and Link php71 ... [OK]
Updating Apache2.4 Configuration /usr/local/etc/httpd/httpd.conf ... [OK]
Restarting Apache2.4 ... [OK]
PHP 7.1.11 (cli) (built: Nov  3 2017 08:48:02) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

3) Finally, when your got above message, check httpd.conf, in my laptop:

vi /usr/local/etc/httpd/httpd.conf

You can see near by LoadModule lines

LoadModule php7_module /usr/local/Cellar/php71/7.1.11_22/libexec/apache2/libphp7.so
#LoadModule php5_module /usr/local/Cellar/php56/5.6.32_8/libexec/apache2/libphp5.so

4) open httpd://localhost/info.php

i hope it helpful

How to change the color of an svg element?

Added a test page - to color SVG via Filter settings:

E.G filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg)

Upload & Color your SVG - Jsfiddle

Took the idea from: https://blog.union.io/code/2017/08/10/img-svg-fill/

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

How to coerce a list object to type 'double'

In this case a loop will also do the job (and is usually sufficiently fast).

a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Extract elements of list at odd positions

list_ = list(range(9)) print(list_[1::2])

Check if a value is in an array (C#)

Not very clear what your issue is, but it sounds like you want something like this:

    List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );

    if( printer.Exists( p => p.Equals( "jupiter" ) ) )
    {
        ...
    }

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

As a general rule (i.e. in vanilla kernels), fork/clone failures with ENOMEM occur specifically because of either an honest to God out-of-memory condition (dup_mm, dup_task_struct, alloc_pid, mpol_dup, mm_init etc. croak), or because security_vm_enough_memory_mm failed you while enforcing the overcommit policy.

Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)

In your particular case, note that Virtuozzo has additional checks in overcommit enforcement. Moreover, I'm not sure how much control you truly have, from within your container, over swap and overcommit configuration (in order to influence the outcome of the enforcement.)

Now, in order to actually move forward I'd say you're left with two options:

  • switch to a larger instance, or
  • put some coding effort into more effectively controlling your script's memory footprint

NOTE that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.

Memory-wise, we already know that subprocess.Popen uses fork/clone under the hood, meaning that every time you call it you're requesting once more as much memory as Python is already eating up, i.e. in the hundreds of additional MB, all in order to then exec a puny 10kB executable such as free or ps. In the case of an unfavourable overcommit policy, you'll soon see ENOMEM.

Alternatives to fork that do not have this parent page tables etc. copy problem are vfork and posix_spawn. But if you do not feel like rewriting chunks of subprocess.Popen in terms of vfork/posix_spawn, consider using suprocess.Popen only once, at the beginning of your script (when Python's memory footprint is minimal), to spawn a shell script that then runs free/ps/sleep and whatever else in a loop parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.

HOWEVER, in your particular case you can skip invoking ps and free altogether; that information is readily available to you in Python directly from procfs, whether you choose to access it yourself or via existing libraries and/or packages. If ps and free were the only utilities you were running, then you can do away with subprocess.Popen completely.

Finally, whatever you do as far as subprocess.Popen is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and check for memory leaks.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

Just this command is enough to do the magic on centos 6.6

mysql_install_db

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How to get index of object by its property in JavaScript?

What about this ? :

Data.indexOf(_.find(Data, function(element) {
  return element.name === 'John';
}));

Assuming you are using lodash or underscorejs.

How to round a floating point number up to a certain decimal place?

You want to use the decimal module but you also need to specify the rounding mode. Here's an example:

>>> import decimal
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP)
Decimal('8.34')
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
Decimal('8.33')
>>> 

Formatting ISODate from Mongodb

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

How do I close a tkinter window?

import sys
from Tkinter import *
def quit():
    sys.exit()
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()

Should do what you are asking.

Best place to insert the Google Analytics code

Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

SQL Bulk Insert with FIRSTROW parameter skips the following line

To let SQL handle quote escape and everything else do this

BULK INSERT Test_CSV
FROM  'C:\MyCSV.csv' 
WITH (
 FORMAT='CSV'
 --FIRSTROW = 2,  --uncomment this if your CSV contains header, so start parsing at line 2
);

In regards to other answers, here is valuable info as well:

I keep seeing this in all answers: ROWTERMINATOR = '\n'
The \n means LF and it is Linux style EOL

In Windows the EOL is made of 2 chars CRLF so you need ROWTERMINATOR = '\r\n'

enter image description here

enter image description here

Set default time in bootstrap-datetimepicker

For use datetime from input value, just set option useCurrent to false, and set in value the date

_x000D_
_x000D_
$('#datetimepicker1').datetimepicker({_x000D_
  useCurrent: false,_x000D_
  format: 'DD.MM.YYYY H:mm'_x000D_
});
_x000D_
_x000D_
_x000D_

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

How to Use slideDown (or show) function on a table row?

Animations are not supported on table rows.

From "Learning jQuery" by Chaffer and Swedberg


Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.


You can wrap your td contents in a div and use the slideDown on that. You need to decide if the animation is worth the extra markup.

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

Where is `%p` useful with printf?

x is Unsigned hexadecimal integer ( 32 Bit )

p is Pointer address

See printf on the C++ Reference. Even if both of them would write the same, I would use %p to print a pointer.

Bootstrap 3 offset on right not left

Since Google seems to like this answer...

If you're looking to match Bootstrap 4's naming convention, i.e. offset-*-#, here's that modification:

.offset-right-12 {
  margin-right: 100%;
}
.offset-right-11 {
  margin-right: 91.66666667%;
}
.offset-right-10 {
  margin-right: 83.33333333%;
}
.offset-right-9 {
  margin-right: 75%;
}
.offset-right-8 {
  margin-right: 66.66666667%;
}
.offset-right-7 {
  margin-right: 58.33333333%;
}
.offset-right-6 {
  margin-right: 50%;
}
.offset-right-5 {
  margin-right: 41.66666667%;
}
.offset-right-4 {
  margin-right: 33.33333333%;
}
.offset-right-3 {
  margin-right: 25%;
}
.offset-right-2 {
  margin-right: 16.66666667%;
}
.offset-right-1 {
  margin-right: 8.33333333%;
}
.offset-right-0 {
  margin-right: 0;
}
@media (min-width: 576px) {
  .offset-sm-right-12 {
    margin-right: 100%;
  }
  .offset-sm-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-sm-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-sm-right-9 {
    margin-right: 75%;
  }
  .offset-sm-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-sm-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-sm-right-6 {
    margin-right: 50%;
  }
  .offset-sm-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-sm-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-sm-right-3 {
    margin-right: 25%;
  }
  .offset-sm-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-sm-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-sm-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 768px) {
  .offset-md-right-12 {
    margin-right: 100%;
  }
  .offset-md-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-md-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-md-right-9 {
    margin-right: 75%;
  }
  .offset-md-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-md-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-md-right-6 {
    margin-right: 50%;
  }
  .offset-md-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-md-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-md-right-3 {
    margin-right: 25%;
  }
  .offset-md-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-md-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-md-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .offset-lg-right-12 {
    margin-right: 100%;
  }
  .offset-lg-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-lg-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-lg-right-9 {
    margin-right: 75%;
  }
  .offset-lg-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-lg-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-lg-right-6 {
    margin-right: 50%;
  }
  .offset-lg-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-lg-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-lg-right-3 {
    margin-right: 25%;
  }
  .offset-lg-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-lg-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-lg-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .offset-xl-right-12 {
    margin-right: 100%;
  }
  .offset-xl-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-xl-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-xl-right-9 {
    margin-right: 75%;
  }
  .offset-xl-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-xl-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-xl-right-6 {
    margin-right: 50%;
  }
  .offset-xl-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-xl-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-xl-right-3 {
    margin-right: 25%;
  }
  .offset-xl-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-xl-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-xl-right-0 {
    margin-right: 0;
  }
}

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

As this video illustrates, creating a repo online first is the usual way to go.

The SourceTree Release Notes do mention for SourceTree 1.5+:

Support creating new repositories under team / organisation accounts in Bitbucket.

So while there is no "publishing" feature, you could create your online repo from SourceTree.

The blog post "SourceTree for Windows 1.2 is here" (Sept 2013) also mention:

Now you can configure your Bitbucket, Stash and GitHub accounts in SourceTree and instantly see all your repositories on those services. Easily clone them, open the project on the web, and even create new repositories on the remote service without ever leaving SourceTree.
You’ll find it in the menu under View > Show Hosted Repositories, or using the new button at the bottom right of the bookmarks panel.

http://blog.sourcetreeapp.com/files/2013/09/hostedrepowindow.png

Unused arguments in R

You could use dots: ... in your function definition.

myfun <- function(a, b, ...){
  cat(a,b)
}

myfun(a=4,b=7,hello=3)

# 4 7

How can I search Git branches for a file or directory?

You could use gitk --all and search for commits "touching paths" and the pathname you are interested in.

Removing cordova plugins from the project

If the above solution didn't work and you got any unhandled promise rejection then try to follow steps :

  1. Clean the Cordova project

    cordova clean

    1. Remove platform

cordova platform remove android/ios

  1. Then remove plugin

cordova plugin remove

  1. add platforms and run the project It worked for me.

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

PHP Redirect to another page after form submit

You can include your header function wherever you like, as long as NO html and/or text has been printed to standard out.

For more information and usage: http://php.net/manual/en/function.header.php


I see in your code that you echo() out some text in case of error or success. Don't do that: you can't. You can only redirect OR show the text. If you show the text you'll then fail to redirect.

IntelliJ shortcut to show a popup of methods in a class that can be searched

Do Cmd+F12+Fn Key on mac in IntelliJ if clicking Cmd+F12 starts.

How to make input type= file Should accept only pdf and xls

While this particular example is for a multiple file upload, it gives the general information one needs:

https://developer.mozilla.org/en-US/docs/DOM/File.type

As far as acting upon a file upon /download/ this is not a Javascript question -- but rather a server configuration. If a user does not have something installed to open PDF or XLS files, their only choice will be to download them.

How to bring back "Browser mode" in IE11?

How to bring back “Browser mode” in IE11?

Easy way to bring back is just go to Emulation (ctrl +8)

and do change user agent string. (see attached image)

enter image description here

Python RuntimeWarning: overflow encountered in long scalars

Here's an example which issues the same warning:

import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a

yields

RuntimeWarning: overflow encountered in long_scalars

In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32.

Note that you can not rely on np.seterr(all='warn') to catch all overflow errors in numpy. For example, on 32-bit NumPy

>>> np.multiply.reduce(np.arange(21)+1)
-1195114496

while on 64-bit NumPy:

>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848

Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals

In [47]: import math

In [48]: math.factorial(21)
Out[50]: 51090942171709440000L

According to numpy developer, Robert Kern,

Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.

So the burden is on you to choose appropriate dtypes so that no operation overflows.

Implement Stack using Two Queues

Here is my solution that works for O(1) in average case. There are two queues: in and out. See pseudocode bellow:

PUSH(X) = in.enqueue(X)

POP: X =
  if (out.isEmpty and !in.isEmpty)
    DUMP(in, out)
  return out.dequeue

DUMP(A, B) =
  if (!A.isEmpty)
    x = A.dequeue()
    DUMP(A, B)
    B.enqueue(x)

How to use NSJSONSerialization

@rckoenes already showed you how to correctly get your data from the JSON string.

To the question you asked: EXC_BAD_ACCESS almost always comes when you try to access an object after it has been [auto-]released. This is not specific to JSON [de-]serialization but, rather, just has to do with you getting an object and then accessing it after it's been released. The fact that it came via JSON doesn't matter.

There are many-many pages describing how to debug this -- you want to Google (or SO) obj-c zombie objects and, in particular, NSZombieEnabled, which will prove invaluable to you in helping determine the source of your zombie objects. ("Zombie" is what it's called when you release an object but keep a pointer to it and try to reference it later.)

How to call C++ function from C?

You can prefix the function declaration with extern “C” keyword, e.g.

extern “C” int Mycppfunction()

{

// Code goes here

return 0;

}

For more examples you can search more on Google about “extern” keyword. You need to do few more things, but it's not difficult you'll get lots of examples from Google.

Using ConfigurationManager to load config from an arbitrary location

For ASP.NET use WebConfigurationManager:

var config = WebConfigurationManager.OpenWebConfiguration("~/Sites/" + requestDomain + "/");
(..)
config.AppSettings.Settings["xxxx"].Value;

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

I had issues getting through a form because of this error.

I used Ctrl+Click to click the submit button and navigate through the form as usual.

How can I get the content of CKEditor using JQuery?

version 4.8.0

$('textarea').data('ckeditorInstance').getData();

Copy all files with a certain extension from all subdirectories

I also had to do this myself. I did it via the --parents argument for cp:

find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;

What is a software framework?

A framework provides functionalities/solution to the particular problem area.
Definition from wiki:

A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.

Django request.GET

from django.http import QueryDict

def search(request):
if request.GET.\__contains__("q"):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'
return HttpResponse(message)

Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/

Excel: How to check if a cell is empty with VBA?

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

Count length of array and return 1 if it only contains one element

A couple other options:

  1. Use the comma operator to create an array:

    $cars = ,"bmw"
    $cars.GetType().FullName
    # Outputs: System.Object[]
    
  2. Use array subexpression syntax:

    $cars = @("bmw")
    $cars.GetType().FullName
    # Outputs: System.Object[]
    

If you don't want an object array you can downcast to the type you want e.g. a string array.

 [string[]] $cars = ,"bmw"
 [string[]] $cars = @("bmw")

How to find which columns contain any NaN value in Pandas dataframe

In datasets having large number of columns its even better to see how many columns contain null values and how many don't.

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))

For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.

Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)

Note: Above code removes all of your null values. If you want null values, process them before.

Repeating a function every few seconds

There are lot of different Timers in the .NET BCL:

When to use which?

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.

Source


Some of them needs explicit Start call to begin ticking (for example System.Timers, System.Windows.Forms). And an explicit Stop to finish ticking.

using TimersTimer = System.Timers.Timer;

static void Main(string[] args)
{
    var timer = new TimersTimer(1000);
    timer.Elapsed += (s, e) => Console.WriteLine("Beep");
    Thread.Sleep(1000); //1 second delay
    timer.Start();
    Console.ReadLine();
    timer.Stop();

}

While on the other hand there are some Timers (like: System.Threading) where you don't need explicit Start and Stop calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.

So, the following two versions will work in the same way:

using ThreadingTimer = System.Threading.Timer;

static void Main(string[] args)
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
    StartTimer();
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

But if your timer disposed then it will stop ticking obviously.

using ThreadingTimer = System.Threading.Timer; 

static void Main(string[] args)
{
    StartTimer();
    GC.Collect(0);
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

Disabling Minimize & Maximize On WinForm?

Set MaximizeBox and MinimizeBox form properties to False

Have nginx access_log and error_log log to STDOUT and STDERR of master process

For a debug purpose:

/usr/sbin/nginx -g "daemon off;error_log /dev/stdout debug;"

For a classic purpose

/usr/sbin/nginx -g "daemon off;error_log /dev/stdout info;"

Require

Under the server bracket on the config file

access_log /dev/stdout;

Moment.js with Vuejs

In your package.json in the "dependencies" section add moment:

"dependencies": {
  "moment": "^2.15.2",
  ...
}

In the component where you would like to use moment, import it:

<script>
import moment from 'moment'
...

And in the same component add a computed property:

computed: {
  timestamp: function () {
    return moment(this.<model>.attributes['created-at']).format('YYYY-MM-DD [at] hh:mm')
  }
}

And then in the template of this component:

<p>{{ timestamp }}</p>

How to split strings into text and number?

I would approach this by using re.match in the following way:

import re
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
    items = match.groups()
print(items)
>> ("foofo", "21")

How Do I Uninstall Yarn

What I've done on my side:

Went to the /usr/local/lib/node_modules, and deleted the yarn folder inside it.

Selenium Webdriver move mouse to Point

the solution is implementing anonymous class in this manner:

        import org.openqa.selenium.Point;
        import org.openqa.selenium.interactions.HasInputDevices;
        import org.openqa.selenium.interactions.Mouse;
        import org.openqa.selenium.interactions.internal.Coordinates;

        .....

        final Point image = page.findImage("C:\\Pictures\\marker.png") ;

        Mouse mouse = ((HasInputDevices) driver).getMouse();

        Coordinates imageCoordinates =  new Coordinates() {

              public Point onScreen() {
                throw new UnsupportedOperationException("Not supported yet.");
              }

              public Point inViewPort() {
                Response response = execute(DriverCommand.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW,
        ImmutableMap.of("id", getId()));

    @SuppressWarnings("unchecked")
    Map<String, Number> mapped = (Map<String, Number>) response.getValue();

    return new Point(mapped.get("x").intValue(), mapped.get("y").intValue());
              }

              public Point onPage() {
                return image;
              }

              public Object getAuxiliary() {
                // extract the selenium imageElement id (imageElement.toString() and parse out the "{sdafbsdkjfh}" format id) and return it
              }
            };

        mouse.mouseMove(imageCoordinates);

Solve error javax.mail.AuthenticationFailedException

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail1 {

    public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
          String to = "valid email to address";

          // Sender's email ID needs to be mentioned
          String from = "valid email from address";


          // Get system properties
          Properties properties = System.getProperties();

          properties.put("mail.smtp.starttls.enable", "true"); 
          properties.put("mail.smtp.host", "smtp.gmail.com");

          properties.put("mail.smtp.port", "587");
          properties.put("mail.smtp.auth", "true");
          Authenticator authenticator = new Authenticator () {
                public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("userid","password");//userid and password for "from" email address 
                }
            };

            Session session = Session.getDefaultInstance( properties , authenticator);  
          try{
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,
                                      new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }catch (MessagingException mex) {
             mex.printStackTrace();
          }
    }

}

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

In my case, when I created a 9.png file, my original PNG file was using the margin where the 9.png line is drawn, creating a bad 9.png file. Try to add some margin to your PNG file.

Mismatched anonymous define() module

I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.

To get rid of the error, include all your other js files by using requirejs.

How to paginate with Mongoose in Node.js?

Here is a version that I attach to all my models. It depends on underscore for convenience and async for performance. The opts allows for field selection and sorting using the mongoose syntax.

var _ = require('underscore');
var async = require('async');

function findPaginated(filter, opts, cb) {
  var defaults = {skip : 0, limit : 10};
  opts = _.extend({}, defaults, opts);

  filter = _.extend({}, filter);

  var cntQry = this.find(filter);
  var qry = this.find(filter);

  if (opts.sort) {
    qry = qry.sort(opts.sort);
  }
  if (opts.fields) {
    qry = qry.select(opts.fields);
  }

  qry = qry.limit(opts.limit).skip(opts.skip);

  async.parallel(
    [
      function (cb) {
        cntQry.count(cb);
      },
      function (cb) {
        qry.exec(cb);
      }
    ],
    function (err, results) {
      if (err) return cb(err);
      var count = 0, ret = [];

      _.each(results, function (r) {
        if (typeof(r) == 'number') {
          count = r;
        } else if (typeof(r) != 'number') {
          ret = r;
        }
      });

      cb(null, {totalCount : count, results : ret});
    }
  );

  return qry;
}

Attach it to your model schema.

MySchema.statics.findPaginated = findPaginated;

XML Schema (XSD) validation tool?

I'm just learning Schema. I'm using RELAX NG and using xmllint to validate. I'm getting frustrated by the errors coming out of xmlllint. I wish they were a little more informative.

If there is a wrong attribute in the XML then xmllint tells you the name of the unsupported attribute. But if you are missing an attribute in the XML you just get a message saying the element can not be validated.

I'm working on some very complicated XML with very complicated rules, and I'm new to this so tracking down which attribute is missing is taking a long time.

Update: I just found a java tool I'm liking a lot. It can be run from the command line like xmllint and it supports RELAX NG: https://msv.dev.java.net/

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

I had the same issue until I added the following lib array in typeScript 3.0.1

tsconfig.json

{
  "compilerOptions": {
    "outDir": "lib",
    "module": "commonjs",
    "allowJs": false,
    "declaration": true,
    "target": "es5",
    "lib": ["dom", "es2015", "es5", "es6"],
    "rootDir": "src"
  },
  "include": ["./**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

Sort ObservableCollection<string> through C#

The argument to OrderByDescending is a function returning a key to sort with. In your case, the key is the string itself:

var result = _animals.OrderByDescending(a => a);

If you wanted to sort by length for example, you'll write:

var result = _animals.OrderByDescending(a => a.Length);

Is Android using NTP to sync time?

Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf - obviously this file can only be edited with root access, but is viewable on non-rooted devices.

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

=INDEX(GoogleFinance("CURRENCY:" & "EUR" & "USD", "price", A2), 2, 2)

where A2 is the cell with a date formatted as date.

Replace "EUR" and "USD" with your currency pair.

How do I get a value of a <span> using jQuery?

You could use id in span directly in your html.

<span id="span_id">Client</span>

Then your jQuery code would be

$("#span_id").text();

Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So

$("#span_id").val();

will return null.

Giving multiple conditions in for loop in Java

A basic for statement includes

  • 0..n initialization statements (ForInit)
  • 0..1 expression statements that evaluate to boolean or Boolean (ForStatement) and
  • 0..n update statements (ForUpdate)

If you need multiple conditions to build your ForStatement, then use the standard logic operators (&&, ||, |, ...) but - I suggest to use a private method if it gets to complicated:

for (int i = 0, j = 0; isMatrixElement(i,j,myArray); i++, j++) { 
   // ...
}

and

private boolean isMatrixElement(i,j,myArray) {
  return (i < myArray.length) && (j < myArray[i].length);  //  stupid dummy code!
}

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

KeyedCollection works like dictionary and is serializable.

First create a class containing key and value:

/// <summary>
/// simple class
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCulture
{
    /// <summary>
    /// culture
    /// </summary>
    public string culture;

    /// <summary>
    /// word list
    /// </summary>
    public List<string> list;

    /// <summary>
    /// status
    /// </summary>
    public string status;
}

then create a class of type KeyedCollection, and define a property of your class as key.

/// <summary>
/// keyed collection.
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCultures : System.Collections.ObjectModel.KeyedCollection<string, cCulture>
{
    protected override string GetKeyForItem(cCulture item)
    {
        return item.culture;
    }
}

Usefull to serialize such type of datas.

Going from MM/DD/YYYY to DD-MMM-YYYY in java

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));

Java 8 LocalDate

Jump to function definition in vim

After generating ctags, you can also use the following in vim:

:tag <f_name>

Above will take you to function definition.

Increment value in mysql update query

Who needs to update string and numbers SET @a = 0; UPDATE obj_disposition SET CODE = CONCAT('CD_', @a:=@a+1);

How can I scale the content of an iframe?

Thought I'd share what I came up with, using much of what was given above. I haven't checked Chrome, but it works in IE, Firefox and Safari, so far as I can tell.

The specifics offsets and zoom factor in this example worked for shrinking and centering two websites in iframes for Facebook tabs (810px width).

The two sites used were a wordpress site and a ning network. I'm not very good with html, so this could probably have been done better, but the result seems good.

<style>
    #wrap { width: 1620px; height: 3500px; padding: 0; position:relative; left:-100px; top:0px; overflow: hidden; }
    #frame { width: 1620px; height: 3500px; position:relative; left:-65px; top:0px; }
    #frame { -ms-zoom: 0.7; -moz-transform: scale(0.7); -moz-transform-origin: 0px 0; -o-transform: scale(0.7); -o-transform-origin: 0 0; -webkit-transform: scale(0.7); -webkit-transform-origin: 0 0; }
</style>
<div id="wrap">
    <iframe id="frame" src="http://www.example.com"></iframe>
</div>

Android LinearLayout : Add border with shadow around a LinearLayout

You create a file .xml in drawable with name drop_shadow.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--<item android:state_pressed="true">
        <layer-list>
            <item android:left="4dp" android:top="4dp">
                <shape>
                    <solid android:color="#35000000" />
                    <corners android:radius="2dp"/>
                </shape>
            </item>
            ...
        </layer-list>
    </item>-->
    <item>
        <layer-list>
            <!-- SHADOW LAYER -->
            <!--<item android:top="4dp" android:left="4dp">
                <shape>
                    <solid android:color="#35000000" />
                    <corners android:radius="2dp" />
                </shape>
            </item>-->
            <!-- SHADOW LAYER -->
            <item>
                <shape>
                    <solid android:color="#35000000" />
                    <corners android:radius="2dp" />
                </shape>
            </item>
            <!-- CONTENT LAYER -->
            <item android:bottom="3dp" android:left="1dp" android:right="3dp" android:top="1dp">
                <shape>
                    <solid android:color="#ffffff" />
                    <corners android:radius="1dp" />
                </shape>
            </item>
        </layer-list>
    </item>
</selector>

Then:

<LinearLayout
...
android:background="@drawable/drop_shadow"/>

How do you display code snippets in MS Word preserving format and syntax highlighting?

This is the simplest approach I follow. Consider I want to paste java code.

  1. I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm

  2. Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/

  3. Then paste the preview code got from step 2 to the MS word. Finally it will look like this

enter image description here

Exception: Can't bind to 'ngFor' since it isn't a known native property

You should use let keyword as to declare local variables e.g *ngFor="let talk of talks"

Lint: How to ignore "<key> is not translated in <language>" errors?

Android Studio:

  • "File" > "Settings" and type "MissingTranslation" into the search box

Eclipse:

  • Windows/Linux: In "Window" > "Preferences" > "Android" > "Lint Error Checking"
  • Mac: "Eclipse" > "Preferences" > "Android" > "Lint Error Checking"

Find the MissingTranslation line, and set it to Warning as seen below:

Missing translations, is not translated in

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

How do I set up cron to run a file just once at a specific time?

You really want to use at. It is exactly made for this purpose.

echo /usr/bin/the_command options | at now + 1 day

However if you don't have at, or your hosting company doesn't provide access to it, you can have a cron job include code that makes sure it only runs once.

Set up a cron entry with a very specific time:

0 0 2 12 * /home/adm/bin/the_command options

Next /home/adm/bin/the_command needs to either make sure it only runs once.

#! /bin/bash

COMMAND=/home/adm/bin/the_command
DONEYET="${COMMAND}.alreadyrun"

export PATH=/usr/bin:$PATH

if [[ -f $DONEYET ]]; then
  exit 1
fi
touch "$DONEYET"

# Put the command you want to run exactly once here:
echo 'You will only get this once!' | mail -s 'Greetings!' [email protected]

require_once :failed to open stream: no such file or directory

It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc doesn't exist, so the error is, you're missing the file.

How are people unit testing with Entity Framework 6, should you bother?

So here's the thing, Entity Framework is an implementation so despite the fact that it abstracts the complexity of database interaction, interacting directly is still tight coupling and that's why it's confusing to test.

Unit testing is about testing the logic of a function and each of its potential outcomes in isolation from any external dependencies, which in this case is the data store. In order to do that, you need to be able to control the behavior of the data store. For example, if you want to assert that your function returns false if the fetched user doesn't meet some set of criteria, then your [mocked] data store should be configured to always return a user that fails to meet the criteria, and vice versa for the opposite assertion.

With that said, and accepting the fact that EF is an implementation, I would likely favor the idea of abstracting a repository. Seem a bit redundant? It's not, because you are solving a problem which is isolating your code from the data implementation.

In DDD, the repositories only ever return aggregate roots, not DAO. That way, the consumer of the repository never has to know about the data implementation (as it shouldn't) and we can use that as an example of how to solve this problem. In this case, the object that is generated by EF is a DAO and as such, should be hidden from your application. This another benefit of the repository that you define. You can define a business object as its return type instead of the EF object. Now what the repo does is hide the calls to EF and maps the EF response to that business object defined in the repos signature. Now you can use that repo in place of the DbContext dependency that you inject into your classes and consequently, now you can mock that interface to give you the control that you need in order to test your code in isolation.

It's a bit more work and many thumb their nose at it, but it solves a real problem. There's an in-memory provider that was mentioned in a different answer that could be an option (I have not tried it), and its very existence is evidence of the need for the practice.

I completely disagree with the top answer because it sidesteps the real issue which is isolating your code and then goes on a tangent about testing your mapping. By all means test your mapping if you want to, but address the actual issue here and get some real code coverage.

Immutable array in Java

As others have noted, you can't have immutable arrays in Java.

If you absolutely need a method that returns an array that doesn't influence the original array, then you'd need to clone the array each time:

public int[] getFooArray() {
  return fooArray == null ? null : fooArray.clone();
}

Obviously this is rather expensive (as you'll create a full copy each time you call the getter), but if you can't change the interface (to use a List for example) and can't risk the client changing your internals, then it may be necessary.

This technique is called making a defensive copy.

Load a UIView from nib in Swift

class func loadFromNib<T: UIView>() -> T {
    let nibName = String(describing: self)
    return Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)![0] as! T
}

Excel formula to get ranking position

Type this to B3, and then pull it to the rest of the rows:

=IF(C3=C2,B2,B2+COUNTIF($C$1:$C3,C2))

What it does is:

  • If my points equals the previous points, I have the same position.
  • Othewise count the players with the same score as the previous one, and add their numbers to the previous player's position.

Delete all lines starting with # or ; in Notepad++

Maybe you should try

^[#;].*$

^ matches the beggining, $ the end.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In case anybody comes back to this, I think the problem here was failing to install the parent pom first, which all these submodules depend on, so the Maven Reactor can't collect the necessary dependencies to build the submodule.

So from the root directory (here D:\luna_workspace\empire_club\empirecl) it probably just needs a:

mvn clean install

(Aside: <relativePath>../pom.xml</relativePath> is not really necessary as it's the default value).

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

Enable gzip compression in php.ini:

zlib.output_compression = On

And add this to your .htaccess file:

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

Loop through all nested dictionary values?

Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield (key, value)
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)

Prints

a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need to go here https://security.google.com/settings/security/apppasswords

then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.

"ssl module in Python is not available" when installing package with pip3

If in windows and using anaconda, than I solved it by first,

conda activate
pip install <lib>

This worked for me.

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

This is due to path not set where keytool.exe present.

Open command prompt in windows machine, traverse where you would like to run keytool cmd and set path where keytool.exe present

Step 1 : Open cmd promt and run "cd C:\Program Files\Java\jdk1.8.0_131\jre\lib\security"

Step 2 : Run below cmd to set path using "set PATH=C:\Program Files\Java\jdk1.8.0_131\bin"

Step 3 : Run keytool cmd, now it will be able to recognize.

How to convert a string or integer to binary in Ruby?

Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

Tricks to manage the available memory in an R session

Ensure you record your work in a reproducible script. From time-to-time, reopen R, then source() your script. You'll clean out anything you're no longer using, and as an added benefit will have tested your code.

How do I find which rpm package supplies a file I'm looking for?

The most popular answer is incomplete:

Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).

yum --disablerepo=* whatprovides <file>

When should null values of Boolean be used?

Use boolean rather than Boolean every time you can. This will avoid many NullPointerExceptions and make your code more robust.

Boolean is useful, for example

  • to store booleans in a collection (List, Map, etc.)
  • to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context.
  • each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like MessageFormat.format().

Assert a function/method was not called using Mock

You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest, you can check the contents of call_args_list instead:

self.assertItemsEqual(my_var.call_args_list, [])

When it fails, it gives a message like this:

AssertionError: Element counts were not equal:
First has 0, Second has 1:  call('first argument', 4)

explicit casting from super class to subclass

Because theoretically Animal animal can be a dog:

Animal animal = new Dog();

Generally, downcasting is not a good idea. You should avoid it. If you use it, you better include a check:

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
}

How to use SVG markers in Google Maps API v3

You can render your icon using the SVG Path notation.

See Google documentation for more information.

Here is a basic example:

var icon = {

    path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
    fillColor: '#FF0000',
    fillOpacity: .6,
    anchor: new google.maps.Point(0,0),
    strokeWeight: 0,
    scale: 1
}

var marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
    draggable: false,
    icon: icon
});

Here is a working example on how to display and scale a marker SVG icon:

JSFiddle demo

Edit:

Another example here with a complex icon:

JSFiddle demo

Edit 2:

And here is how you can have a SVG file as an icon:

JSFiddle demo

String comparison technique used by Python

Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).

To reply to the comment

What? How else can ordering be defined other than left-to-right?

by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.

And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.

Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!

Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).

Concatenating variables and strings in React

exampleData=

        const json1 = [
            {id: 1, test: 1},
            {id: 2, test: 2},
            {id: 3, test: 3},
            {id: 4, test: 4},
            {id: 5, test: 5}
        ];

        const json2 = [
            {id: 3, test: 6},
            {id: 4, test: 7},
            {id: 5, test: 8},
            {id: 6, test: 9},
            {id: 7, test: 10}
        ];

example1=


        const finalData1 = json1.concat(json2).reduce(function (index, obj) {
            index[obj.id] = Object.assign({}, obj, index[obj.id]);
            return index;
        }, []).filter(function (res, obj) {
            return obj;
        });

example2=

        let hashData = new Map();

        json1.concat(json2).forEach(function (obj) {
            hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
        });

        const finalData2 = Array.from(hashData.values());

I recommend second example , it is faster.

How can I check Drupal log files?

To view entries in Drupal's own internal log system (the watchdog database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.

Use the watchdog() function to add an entry to this log from your own custom module.

When Drupal bootstraps it uses the PHP function set_error_handler() to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog() call at admin/reports/dblog. If you look for PHP fatal errors, for example, in /var/log/apache/error.log and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log, or wherever you have it configured to log to.

How to use table variable in a dynamic sql statement?

Your EXEC executes in a different context, therefore it is not aware of any variables that have been declared in your original context. You should be able to use a temp table instead of a table variable as shown in the simple demo below.

create table #t (id int)

declare @value nchar(1)
set @value = N'1'

declare @sql nvarchar(max)
set @sql = N'insert into #t (id) values (' + @value + N')'

exec (@sql)

select * from #t

drop table #t

Tips for using Vim as a Java IDE?

Use vim. ^-^ (gVim, to be precise)

You'll have it all (with some plugins).

Btw, snippetsEmu is a nice tool for coding with useful snippets (like in TextMate). You can use (or modify) a pre-made package or make your own.

Update built-in vim on Mac OS X

I just installed vim by:

brew install vim

now the new vim is accessed by vim and the old vim (built-in vim) by vi

How to delete object?

What you're asking is not possible. There is no mechanism in .Net that would set all references to some object to null.

And I think that the fact that you're trying to do this indicates some sort of design problem. You should probably think about the underlying problem and solve it in another way (the other answers here suggest some options).

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

How do I generate a random int number?

You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a pseudo-random number.

using MiscUtil;
...

for (int i = 0; i < 100; 
    Console.WriteLine(StaticRandom.Next());

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Use Object.entries to get each element of Object in key & value format, then map through them like this:

_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}_x000D_
_x000D_
var res = Object.entries(obj).map(([k, v]) => ([Number(k), v]));_x000D_
_x000D_
console.log(res);
_x000D_
_x000D_
_x000D_

But, if you are certain that the keys will be in progressive order you can use Object.values and Array#map to do something like this:

_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}; _x000D_
_x000D_
                        // idx is the index, you can use any logic to increment it (starts from 0)_x000D_
let result = Object.values(obj).map((e, idx) => ([++idx, e]));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Swift apply .uppercaseString to only the first letter of a string

From Swift 3 you can easily use textField.autocapitalizationType = UITextAutocapitalizationType.sentences

Parse JSON String into a Particular Object Prototype in JavaScript

The currently accepted answer wasn't working for me. You need to use Object.assign() properly:

class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    greet(){
        return `hello my name is ${ this.name } and i am ${ this.age } years old`;
    }
}

You create objects of this class normally:

let matt = new Person('matt', 12);
console.log(matt.greet()); // prints "hello my name is matt and i am 12 years old"

If you have a json string you need to parse into the Person class, do it like so:

let str = '{"name": "john", "age": 15}';
let john = JSON.parse(str); // parses string into normal Object type

console.log(john.greet()); // error!!

john = Object.assign(Person.prototype, john); // now john is a Person type
console.log(john.greet()); // now this works

Undoing a git rebase

Using reflog didn't work for me.

What worked for me was similar to as described here. Open the file in .git/logs/refs named after the branch that was rebased and find the line that contains "rebase finsihed", something like:

5fce6b51 88552c8f Kris Leech <[email protected]> 1329744625 +0000  rebase finished: refs/heads/integrate onto 9e460878

Checkout the second commit listed on the line.

git checkout 88552c8f

Once confirmed this contained my lost changes I branched and let out a sigh of relief.

git log
git checkout -b lost_changes

Calling virtual functions inside constructors

Do you know the crash error from Windows explorer?! "Pure virtual function call ..."
Same problem ...

class AbstractClass 
{
public:
    AbstractClass( ){
        //if you call pureVitualFunction I will crash...
    }
    virtual void pureVitualFunction() = 0;
};

Because there is no implemetation for the function pureVitualFunction() and the function is called in the constructor the program will crash.

How to consume a webApi from asp.net Web API to store result in database?

For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsStringAsync();
    var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.

Importing files from different folder

Worked for me in python3 on linux

import sys  
sys.path.append(pathToFolderContainingScripts)  
from scriptName import functionName #scriptName without .py extension  

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

how to use javascript Object.defineProperty

Basically, defineProperty is a method that takes in 3 parameters - an object, a property, and a descriptor. What is happening in this particular call is the "health" property of the player object is getting assigned to 10 plus 15 times that player object's level.

How to auto generate migrations with Sequelize CLI from Sequelize models?

You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations

Using sequelize-cli, initialize your project with

sequelize init

Create your models and put them in your models folder.

Install sequelize-auto-migrations:

npm install sequelize-auto-migrations

Create an initial migration file with

node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>

Run your migration:

node ./node_modules/sequelize-auto-migrations/bin/runmigration

You can also automatically generate your models from an existing database, but that is beyond the scope of the question.

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular 4 img src is not found

Check in your.angular-cli.json under app -> assets:[] if you have included assets folder.

Or perhaps something here: https://github.com/angular/angular-cli/issues/2231, can help.

How to install mod_ssl for Apache httpd?

Are any other LoadModule commands referencing modules in the /usr/lib/httpd/modules folder? If so, you should be fine just adding LoadModule ssl_module /usr/lib/httpd/modules/mod_ssl.so to your conf file.

Otherwise, you'll want to copy the mod_ssl.so file to whatever directory the other modules are being loaded from and reference it there.

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

(Updated - Thanks to the people who commented)

Modern Versions of PostgreSQL

Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:

   ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

Older Versions of PostgreSQL

In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:

  ALTER TABLE test1 ADD COLUMN id INTEGER;
  CREATE SEQUENCE test_id_seq OWNED BY test1.id;
  ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
  UPDATE test1 SET id = nextval('test_id_seq');

Again, in recent versions of Postgres this is roughly equivalent to the single command above.

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

How do I make a redirect in PHP?

To redirect in php:

<?php header('Location: URL'); exit; ?>

Check orientation on Android phone

i think using getRotationv() doesn't help because http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation() Returns the rotation of the screen from its "natural" orientation.

so unless you know the "natural" orientation, rotation is meaningless.

i found an easier way,

  Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  int width = size.x;
  int height = size.y;
  if(width>height)
    // its landscape

please tell me if there is a problem with this someone?

Java 8 List<V> into Map<K, V>

This can be done in 2 ways. Let person be the class we are going to use to demonstrate it.

public class Person {

    private String name;
    private int age;

    public String getAge() {
        return age;
    }
}

Let persons be the list of Persons to be converted to the map

1.Using Simple foreach and a Lambda Expression on the List

Map<Integer,List<Person>> mapPersons = new HashMap<>();
persons.forEach(p->mapPersons.put(p.getAge(),p));

2.Using Collectors on Stream defined on the given List.

 Map<Integer,List<Person>> mapPersons = 
           persons.stream().collect(Collectors.groupingBy(Person::getAge));

Java and SQLite

Typo: java -cp .:sqlitejdbc-v056.jar Test

should be: java -cp .:sqlitejdbc-v056.jar; Test

notice the semicolon after ".jar" i hope that helps people, could cause a lot of hassle

Getting full JS autocompletion under Sublime Text

As of today (November 2019), Microsoft's TypeScript plugin does what the OP required: https://packagecontrol.io/packages/TypeScript.

How to return a custom object from a Spring Data JPA GROUP BY query

This SQL query return List< Object[] > would.

You can do it this way:

 @RestController
 @RequestMapping("/survey")
 public class SurveyController {

   @Autowired
   private SurveyRepository surveyRepository;

     @RequestMapping(value = "/find", method =  RequestMethod.GET)
     public Map<Long,String> findSurvey(){
       List<Object[]> result = surveyRepository.findSurveyCount();
       Map<Long,String> map = null;
       if(result != null && !result.isEmpty()){
          map = new HashMap<Long,String>();
          for (Object[] object : result) {
            map.put(((Long)object[0]),object[1]);
          }
       }
     return map;
     }
 }

Passing an array/list into a Python function

You don't need to use the asterisk to accept a list.

Simply give the argument a name in the definition, and pass in a list like

def takes_list(a_list):
    for item in a_list:
         print item

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

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

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

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):

function scrollIntoView(element, container) {
  var containerTop = $(container).scrollTop(); 
  var containerBottom = containerTop + $(container).height(); 
  var elemTop = element.offsetTop;
  var elemBottom = elemTop + $(element).height(); 
  if (elemTop < containerTop) {
    $(container).scrollTop(elemTop);
  } else if (elemBottom > containerBottom) {
    $(container).scrollTop(elemBottom - $(container).height());
  }
}

Make outer div be automatically the same height as its floating content

First of all you don't use width=300px that's an attribute setting for the tag not CSS, use width: 300px; instead.

I would suggest applying the clearfix technique on the #outerdiv. Clearfix is a general solution to clear 2 floating divs so the parent div will expand to accommodate the 2 floating divs.

<div id='outerdiv' class='clearfix' style='width:600px; background-color: black;'>
    <div style='width:300px; float: left;'>
        <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
    </div>

    <div style='width:300px; float: left;'>
        <p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
    </div>
</div>

Here is an example of your situation and what Clearfix does to resolve it.

filename.whl is not supported wheel on this platform

In my case [Win64, Python 2.7, cygwin] the issue was with a missing gcc.

Using apt-cyg install gcc-core enabled me to then use pip2 wheel ... to install my wheels automatically.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

This has happened to me after I "updated" into 5.0 SDK and wanted to create a new application with support library

In both Projects (project.properties file) in the one you want to use support library and the support library itself it has to be set the same target

e.g. for my case it worked

  1. In project android-support-v7-appcompat Change project.properties into target=android-21
  2. Cleanandroid-support-v7-appcompat In my project (where I desire support library)
  3. In my project, Change project.properties into target=android-21 and android.library.reference.1=../android-support-v7-appcompat (or add support library in project properties)
  4. Clean the project

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

How to describe "object" arguments in jsdoc?

If a parameter is expected to have a specific property, you can document that property by providing an additional @param tag. For example, if an employee parameter is expected to have name and department properties, you can document it as follows:

/**
 * Assign the project to a list of employees.
 * @param {Object[]} employees - The employees who are responsible for the project.
 * @param {string} employees[].name - The name of an employee.
 * @param {string} employees[].department - The employee's department.
 */
function(employees) {
    // ...
}

If a parameter is destructured without an explicit name, you can give the object an appropriate one and document its properties.

/**
 * Assign the project to an employee.
 * @param {Object} employee - The employee who is responsible for the project.
 * @param {string} employee.name - The name of the employee.
 * @param {string} employee.department - The employee's department.
 */
Project.prototype.assign = function({ name, department }) {
    // ...
};

Source: JSDoc

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

As noted in the official documentation, simply apply the class(es) btn btn-link:

<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>

For example, with the code you have provided:

_x000D_
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
  <div class="row-fluid">_x000D_
    <!-- Navigation for the form -->_x000D_
    <div class="span3">_x000D_
      <ul class="nav nav-tabs nav-stacked">_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
        </li>_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
        </li>_x000D_
        <!-- ... -->_x000D_
      </ul>_x000D_
    </div>_x000D_
    <!-- The actual form -->_x000D_
    <div class="span9">_x000D_
      <!-- ... -->_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

What is the canonical way to trim a string in Ruby without creating a new string?

I think your example is a sensible approach, although you could simplify it slightly as:

@title = tokens[Title].strip! || tokens[Title] if tokens[Title]

Alternative you could put it on two lines:

@title = tokens[Title] || ''
@title.strip!

How do you get the contextPath from JavaScript, the right way?

Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:

<script>var ctx = "${pageContext.request.contextPath}"</script>

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

When I upgraded Visual Studio to version 15.5.1, .Net Core SDK was upgraded to 2.X, so this error went away. When I run dotnet --info, I see the following now:

enter image description here

How to let an ASMX file output JSON

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

Upload artifacts to Nexus, without Maven

Using curl:

curl -v \
    -F "r=releases" \
    -F "g=com.acme.widgets" \
    -F "a=widget" \
    -F "v=0.1-1" \
    -F "p=tar.gz" \
    -F "file=@./widget-0.1-1.tar.gz" \
    -u myuser:mypassword \
    http://localhost:8081/nexus/service/local/artifact/maven/content

You can see what the parameters mean here: https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-

To make the permissions for this work, I created a new role in the admin GUI and I added two privileges to that role: Artifact Download and Artifact Upload. The standard "Repo: All Maven Repositories (Full Control)"-role is not enough. You won't find this in the REST API documentation that comes bundled with the Nexus server, so these parameters might change in the future.

On a Sonatype JIRA issue, it was mentioned that they "are going to overhaul the REST API (and the way it's documentation is generated) in an upcoming release, most likely later this year".

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

Why is there an unexplainable gap between these inline-block div elements?

The easiest fix is to just float the container. (eg. float: left;) On another note, each id should be unique, meaning you can't use the same id twice in the same HTML document. You should use classes instead, where you can use the same class for multiple elements.

.container {
    position: relative;
    background: rgb(255, 100, 0);
    margin: 0;
    width: 40%;
    height: 100px;
    float: left;
}

How to run a .awk file?

Put the part from BEGIN....END{} inside a file and name it like my.awk.

And then execute it like below:

awk -f my.awk life.csv >output.txt

Also I see a field separator as ,. You can add that in the begin block of the .awk file as FS=","

Checking if a key exists in a JS object

var obj = {
    "key1" : "k1",
    "key2" : "k2",
    "key3" : "k3"
};

if ("key1" in obj)
    console.log("has key1 in obj");

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

To access a child key of another key

var obj = {
    "key1": "k1",
    "key2": "k2",
    "key3": "k3",
    "key4": {
        "keyF": "kf"
    }
};

if ("keyF" in obj.key4)
    console.log("has keyF in obj");

How to calculate probability in a normal distribution given mean & standard deviation?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the probability density function (pdf - likelihood that a random sample X will be near the given value x) for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=100, sigma=12).pdf(98)
# 0.032786643008494994

Also note that the NormalDist object also provides the cumulative distribution function (cdf - probability that a random sample X will be less than or equal to x):

NormalDist(mu=100, sigma=12).cdf(98)
# 0.43381616738909634

How can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

How can I get a resource content from a static context?

public Static Resources mResources;

 @Override
     public void onCreate()
     {
           mResources = getResources();
     }

Oracle 11g Express Edition for Windows 64bit?

Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.

Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.

PHP: trying to create a new line with "\n"

We can apply \n in php by using two type

  1. Using CSS

    body {
        white-space: pre-wrap;
    }
    

    Which tells the browser to preserve whitespace so that

    <body>
        <?php
            echo "Fo\n Pro";
        ?>
    </body>
    

    Result:

    Fo
    Pro

  2. Using nl2br

    nl2br: Inserts HTML line breaks before all newlines in a string

    <?php
        echo nl2br("Fo.\nPro.");
    ?>
    

    Result

    Fo.
    Pro.

Tomcat is not running even though JAVA_HOME path is correct

I think that your JAVA_HOME should point to

C:\Program Files\Java\jdk1.6.0_25

instead of

C:\Program Files\Java\jdk1.6.0_25\bin

That is, without the bin folder.

UPDATE

That new error appears to me if I set the JAVA_HOME with the quotes, like you did. Are you using quotation marks? If so, remove them.

Inconsistent Accessibility: Parameter type is less accessible than method

After updating my entity framework model, I found this error infecting several files in my solution. I simply right clicked on my .edmx file and my TT file and click "Run Custom Tool" and that had me right again after a restart of Visual Studio 2012.

How to insert TIMESTAMP into my MySQL table?

You do not need to insert the current timestamp manually as MySQL provides this facility to store it automatically. When the MySQL table is created, simply do this:

  • select TIMESTAMP as your column type
  • set the Default value to CURRENT_TIMESTAMP
  • then just insert any rows into the table without inserting any values for the time column

You'll see the current timestamp is automatically inserted when you insert a row. Please see the attached picture. enter image description here

Invalid date in safari

How about hijack Date with fix-date? No dependencies, min + gzip = 280 B

Use a content script to access the page context variables and functions

I've also faced the problem of ordering of loaded scripts, which was solved through sequential loading of scripts. The loading is based on Rob W's answer.

function scriptFromFile(file) {
    var script = document.createElement("script");
    script.src = chrome.extension.getURL(file);
    return script;
}

function scriptFromSource(source) {
    var script = document.createElement("script");
    script.textContent = source;
    return script;
}

function inject(scripts) {
    if (scripts.length === 0)
        return;
    var otherScripts = scripts.slice(1);
    var script = scripts[0];
    var onload = function() {
        script.parentNode.removeChild(script);
        inject(otherScripts);
    };
    if (script.src != "") {
        script.onload = onload;
        document.head.appendChild(script);
    } else {
        document.head.appendChild(script);
        onload();
    }
}

The example of usage would be:

var formulaImageUrl = chrome.extension.getURL("formula.png");
var codeImageUrl = chrome.extension.getURL("code.png");

inject([
    scriptFromSource("var formulaImageUrl = '" + formulaImageUrl + "';"),
    scriptFromSource("var codeImageUrl = '" + codeImageUrl + "';"),
    scriptFromFile("EqEditor/eq_editor-lite-17.js"),
    scriptFromFile("EqEditor/eq_config.js"),
    scriptFromFile("highlight/highlight.pack.js"),
    scriptFromFile("injected.js")
]);

Actually, I'm kinda new to JS, so feel free to ping me to the better ways.

PHP: Calling another class' method

If they are separate classes you can do something like the following:

class A
{
    private $name;

    public function __construct()
    {
        $this->name = 'Some Name';
    }

    public function getName()
    {
        return $this->name;
    }
}

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    function getNameOfA()
    {
        return $this->a->getName();
    }
}

$a = new A();
$b = new B($a);

$b->getNameOfA();

What I have done in this example is first create a new instance of the A class. And after that I have created a new instance of the B class to which I pass the instance of A into the constructor. Now B can access all the public members of the A class using $this->a.

Also note that I don't instantiate the A class inside the B class because that would mean I tighly couple the two classes. This makes it hard to:

  1. unit test your B class
  2. swap out the A class for another class

Selecting only first-level elements in jquery

Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root.

$('ul#root').children('li');

How to get a random number between a float range?

if you want generate a random float with N digits to the right of point, you can make this :

round(random.uniform(1,2), N)

the second argument is the number of decimals.

MySQL error 1241: Operand should contain 1 column(s)

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

javascript - replace dash (hyphen) with a space

This fixes it:

let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);

There were two problems with your code:

  1. First, String.replace() doesn’t change the string itself, it returns a changed string.
  2. Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.