Programs & Examples On #Dmd

Dmd stands for the Digital Mars D compiler.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.

The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.

(The below code is 32-bit, but can be easily converted to 64-bit)

For example, the sequence function can be optimized to only 5 instructions:

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

The whole code looks like:

include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"

start:
        InitializeAll
        mov ecx, 999999
        xor edi, edi        ; max
        xor ebx, ebx        ; max i

    .main_loop:

        xor     esi, esi
        mov     eax, ecx

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

        cmp     edi, esi
        cmovb   edi, esi
        cmovb   ebx, ecx

        dec     ecx
        jnz     .main_loop

        OutputValue "Max sequence: ", edi, 10, -1
        OutputValue "Max index: ", ebx, 10, -1

        FinalizeAll
        stdcall TerminateAll, 0

In order to compile this code, FreshLib is needed.

In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3.

The output of both programs is the same: max sequence = 525 on i = 837799.

How to install latest version of openssl Mac OS X El Capitan

You can run brew link openssl to link it into /usr/local, if you don't mind the potential problem highlighted in the warning message. Otherwise, you can add the openssl bin directory to your path:

export PATH=$(brew --prefix openssl)/bin:$PATH

Python base64 data decode

base64 encode/decode example:

import base64

mystr = 'O João mordeu o cão!'

# Encode
mystr_encoded = base64.b64encode(mystr.encode('utf-8'))
# b'TyBKb8OjbyBtb3JkZXUgbyBjw6NvIQ=='

# Decode
mystr_encoded = base64.b64decode(mystr_encoded).decode('utf-8')
# 'O João mordeu o cão!'

How do you decompile a swf file

Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text

What is the best way to remove a table row with jQuery?

$('tr').click(function()
 {
  $(this).remove();
 });

i think you will try the above code, as it work, but i don't know why it work for sometime and then the whole table is removed. i am also trying to remove the row by click the row. but could not find exact answer.

Ordering issue with date values when creating pivot tables

April 20, 2017

I've read all the previously posted answers, and they require a lot of extra work. The quick and simple solution I have found is as follows:

1) Un-group the date field in the pivot table. 2) Go to the Pivot Field List UI. 3) Re-arrange your fields so that the Date field is listed FIRST in the ROWS section. 4) Under the Design menu, select Report Layout / Show in Tabular Form.

By default, Excel sorts by the first field in a pivot table. You may not want the Date field to be first, but it's a compromise that will save you time and much work.

How do I configure Apache 2 to run Perl CGI scripts?

You'll need to take a look at your Apache error log to see what the "internal server error" is. The four most likely cases, in my experience would be:

  1. The CGI program is in a directory which does not have CGI execution enabled. Solution: Add the ExecCGI option to that directory via either httpd.conf or a .htaccess file.

  2. Apache is only configured to run CGIs from a dedicated cgi-bin directory. Solution: Move the CGI program there or add an AddHandler cgi-script .cgi statement to httpd.conf.

  3. The CGI program is not set as executable. Solution (assuming a *nix-type operating system): chmod +x my_prog.cgi

  4. The CGI program is exiting without sending headers. Solution: Run the program from the command line and verify that a) it actually runs rather than dying with a compile-time error and b) it generates the correct output, which should include, at the very minimum, a Content-Type header and a blank line following the last of its headers.

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

target.Value will give you a Variant type

target.Value2 will give you a Variant type as well but a Date is coerced to a Double

target.Text attempts to coerce to a String and will fail if the underlying Variant is not coercable to a String type

The safest thing to do is something like

Dim v As Variant
v = target.Value 'but if you don't want to handle date types use Value2

And check the type of the variant using VBA.VarType(v) before you attempt an explicit coercion.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

It's all about data types. Take a BOOL (true or false) for example:

true also equals 1 and false also equals 0

The == does not care about the data types when comparing: So if you had a variable that is 1 (which could also be true):

$var=1;

And then compare with the ==:

if ($var == true)
{
    echo"var is true";
}

But $var does not actually equal true, does it? It has the int value of 1 instead, which in turn, is equal to true.

With ===, the data types are checked to make sure the two variables/objects/whatever are using the same type.

So if I did

if ($var === true)
{
    echo "var is true";
}

that condition would not be true, as $var !== true it only == true (if you know what I mean).

Why would you need this?

Simple - let's take a look at one of PHP's functions: array_search():

The array_search() function simply searches for a value in an array, and returns the key of the element the value was found in. If the value could not be found in the array, it returns false. But, what if you did an array_search() on a value that was stored in the first element of the array (which would have the array key of 0)....the array_search() function would return 0...which is equal to false..

So if you did:

$arr = array("name");
if (array_search("name", $arr) == false)
{
    // This would return 0 (the key of the element the val was found
    // in), but because we're using ==, we'll think the function
    // actually returned false...when it didn't.
}

So, do you see how this could be an issue now?

Most people don't use == false when checking if a function returns false. Instead, they use the !. But actually, this is exactly the same as using ==false, so if you did:

$arr = array("name");
if (!array_search("name", $arr)) // This is the same as doing (array_search("name", $arr) == false)

So for things like that, you would use the === instead, so that the data type is checked.

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

Package doesn't exist error in intelliJ

Here is a solution worked for me: Disable the "Use --release option for cross-compilation like the following in intellij idea: got Settings -> Build,Execution,Deployment -> Compiler -> Java Compiler and disable:

Use '--release' option for cross compilation(java 9 and later)

Hide separator line on one UITableViewCell

To follow up on Hiren's answer.

in ViewDidLoad and the following line :

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

Or, if you are using XIB's or Storyboards change "separator" to "none" :

Interface builder

And in CellForRowAtIndexPath add this :

CGFloat separatorInset; // Separator x position 
CGFloat separatorHeight; 
CGFloat separatorWidth; 
CGFloat separatorY; 
UIImageView *separator;
UIColor *separatorBGColor;

separatorY      = cell.frame.size.height;
separatorHeight = (1.0 / [UIScreen mainScreen].scale);  // This assures you to have a 1px line height whatever the screen resolution
separatorWidth  = cell.frame.size.width;
separatorInset  = 15.0f;
separatorBGColor  = [UIColor colorWithRed: 204.0/255.0 green: 204.0/255.0 blue: 204.0/255.0 alpha:1.0];

separator = [[UIImageView alloc] initWithFrame:CGRectMake(separatorInset, separatorY, separatorWidth,separatorHeight)];
separator.backgroundColor = separatorBGColor;
[cell addSubView: separator];

Here is an example of the result where I display a tableview with dynamic Cells (but only have a single one with contents). The result being that only that one has a separator and not all the "dummy" ones tableview automatically adds to fill the screen.

enter image description here

Hope this helps.

EDIT: For those who don't always read the comments, there actually is a better way to do it with a few lines of code :

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()
}

How to calculate difference between two dates in oracle 11g SQL

Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).

The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say

select trunc(sysdate) - 1/24/60/60 from dual;

That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.

How do I center text horizontally and vertically in a TextView?

If you are using Relative Layout:

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stringname"
    android:layout_centerInParent="true"/>

If you are using LinearLayout

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stringname"
    android:layout_gravity="center"/>

How to delete from select in MySQL?

DELETE 
  p1
  FROM posts AS p1 
CROSS JOIN (
  SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)

throwing an exception in objective-c/cocoa

You can use two methods for raising exception in the try catch block

@throw[NSException exceptionWithName];

or the second method

NSException e;
[e raise];

List directory in Go

We can get a list of files inside a folder on the file system using various golang standard library functions.

  1. filepath.Walk
  2. ioutil.ReadDir
  3. os.File.Readdir

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
)

func main() {
    var (
        root  string
        files []string
        err   error
    )

    root := "/home/manigandan/golang/samples"
    // filepath.Walk
    files, err = FilePathWalkDir(root)
    if err != nil {
        panic(err)
    }
    // ioutil.ReadDir
    files, err = IOReadDir(root)
    if err != nil {
        panic(err)
    }
    //os.File.Readdir
    files, err = OSReadDir(root)
    if err != nil {
        panic(err)
    }

    for _, file := range files {
        fmt.Println(file)
    }
}
  1. Using filepath.Walk

The path/filepath package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.

func FilePathWalkDir(root string) ([]string, error) {
    var files []string
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if !info.IsDir() {
            files = append(files, path)
        }
        return nil
    })
    return files, err
}
  1. Using ioutil.ReadDir

ioutil.ReadDir reads the directory named by dirname and returns a list of directory entries sorted by filename.

func IOReadDir(root string) ([]string, error) {
    var files []string
    fileInfo, err := ioutil.ReadDir(root)
    if err != nil {
        return files, err
    }

    for _, file := range fileInfo {
        files = append(files, file.Name())
    }
    return files, nil
}
  1. Using os.File.Readdir

Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

func OSReadDir(root string) ([]string, error) {
    var files []string
    f, err := os.Open(root)
    if err != nil {
        return files, err
    }
    fileInfo, err := f.Readdir(-1)
    f.Close()
    if err != nil {
        return files, err
    }

    for _, file := range fileInfo {
        files = append(files, file.Name())
    }
    return files, nil
}

Benchmark results.

benchmark score

Get more details on this Blog Post

Standard Android menu icons, for example refresh

After seeing this post I found a useful link:

http://developer.android.com/design/downloads/index.html

You can download a lot of sources editable with Fireworks, Illustrator, Photoshop, etc...
And there's also fonts and icon packs.

Here is a stencil example.

Setting the character encoding in form submit for Internet Explorer

There is a simple hack to this:

Insert a hidden input field in the form with an entity which only occur in the character set the server your posting (or doing a GET) to accepts.

Example: If the form is located on a server serving ISO-8859-1 and the form will post to a server expecting UTF-8 insert something like this in the form:

<input name="iehack" type="hidden" value="&#9760;" />

IE will then "detect" that the form contains a UTF-8 character and use UTF-8 when you POST or GET. Strange, but it does work.

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

problem with <select> and :after with CSS in WebKit

This post may help http://bavotasan.com/2011/style-select-box-using-only-css/

He is using a outside div with a class for resolving this issue.

<div class="styled-select">
  <select>
    <option>Here is the first option</option>
    <option>The second option</option>
  </select>
</div>

How to read and write INI file with Python3?

There are some problems I found when used configparser such as - I got an error when I tryed to get value from param:

destination=\my-server\backup$%USERNAME%

It was because parser can't get this value with special character '%'. And then I wrote a parser for reading ini files based on 're' module:

import re

# read from ini file.
def ini_read(ini_file, key):
    value = None
    with open(ini_file, 'r') as f:
        for line in f:
            match = re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I)
            if match:
                value = match.group()
                value = re.sub(r'^ *' + key + ' *= *', '', value)
                break
    return value


# read value for a key 'destination' from 'c:/myconfig.ini'
my_value_1 = ini_read('c:/myconfig.ini', 'destination')

# read value for a key 'create_destination_folder' from 'c:/myconfig.ini'
my_value_2 = ini_read('c:/myconfig.ini', 'create_destination_folder')


# write to an ini file.
def ini_write(ini_file, key, value, add_new=False):
    line_number = 0
    match_found = False
    with open(ini_file, 'r') as f:
        lines = f.read().splitlines()
    for line in lines:
        if re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I):
            match_found = True
            break
        line_number += 1
    if match_found:
        lines[line_number] = key + ' = ' + value
        with open(ini_file, 'w') as f:
            for line in lines:
                f.write(line + '\n')
        return True
    elif add_new:
        with open(ini_file, 'a') as f:
            f.write(key + ' = ' + value)
        return True
    return False


# change a value for a key 'destination'.
ini_write('my_config.ini', 'destination', '//server/backups$/%USERNAME%')

# change a value for a key 'create_destination_folder'
ini_write('my_config.ini', 'create_destination_folder', 'True')

# to add a new key, we need to use 'add_new=True' option.
ini_write('my_config.ini', 'extra_new_param', 'True', True)

SQL query to check if a name begins and ends with a vowel

in Microsoft SQL server you can achieve this from below query:

SELECT distinct City FROM STATION WHERE City LIKE '[AEIOU]%[AEIOU]'

Or

SELECT distinct City FROM STATION WHERE City LIKE '[A,E,I,O,U]%[A,E,I,O,U]'

Update --Added Oracle Query

--Way 1 --It should work in all Oracle versions

SELECT DISTINCT CITY FROM STATION WHERE REGEXP_LIKE(LOWER(CITY), '^[aeiou]') and  REGEXP_LIKE(LOWER(CITY), '[aeiou]$');

--Way 2 --it may fail in some versions of Oracle

SELECT DISTINCT CITY FROM STATION WHERE REGEXP_LIKE(LOWER(CITY), '^[aeiou].*[aeiou]');

--Way 3 --it may fail in some versions of Oracle

SELECT DISTINCT CITY FROM STATION WHERE REGEXP_LIKE(CITY, '^[aeiou].*[aeiou]', 'i');

Java: how do I check if a Date is within a certain range?

This was clearer to me,

// declare calendar outside the scope of isWithinRange() so that we initialize it only once
private Calendar calendar = Calendar.getInstance();

public boolean isWithinRange(Date date, Date startDate, Date endDate) {

    calendar.setTime(startDate);
    int startDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); // first day is 1, last day is 365
    int startYear = calendar.get(Calendar.YEAR);

    calendar.setTime(endDate);
    int endDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
    int endYear = calendar.get(Calendar.YEAR);

    calendar.setTime(date);
    int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
    int year = calendar.get(Calendar.YEAR);

    return (year > startYear && year < endYear) // year is within the range
            || (year == startYear && dayOfYear >= startDayOfYear) // year is same as start year, check day as well
            || (year == endYear && dayOfYear < endDayOfYear); // year is same as end year, check day as well

}

Reset par to the default values at startup

From Quick-R

par()              # view current settings
opar <- par()      # make a copy of current settings
par(col.lab="red") # red x and y labels 
hist(mtcars$mpg)   # create a plot with these new settings 
par(opar)          # restore original settings

libpthread.so.0: error adding symbols: DSO missing from command line

Try to add -pthread at the end of the library list in the Makefile.

It worked for me.

Python convert tuple to string

Use str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

How to create a laravel hashed password

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

The name 'model' does not exist in current context in MVC3

I ran into this problem as well. My circumstances were a little different.

  1. One of my view folders was accidentally moved to my project's root directory. This lead to the route project_root/SignUp/ViewName matching before project_root/Views/SignUp/ViewName. This caused the @model error.

  2. After moving the views back into the appropriate location, the directory was somehow recreated in the project root. This time, empty. /SignUp/ViewName worked, but /SignUp/ threw a 403 - Forbidden: Access is denied. error. The entire folder must be removed from the project root.

I hope this helps someone. I spent hours believing the problem was caused by our recent upgrade from MVC 3 to MVC 4. Just a note: Upgrade problems should only occur between MVC 2 and MVC 3. If you see this problem on later versions, it's probably not due to the upgrade.

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

How to create a oracle sql script spool file

With spool:

  set heading off
  set arraysize 1
  set newpage 0
  set pages 0
  set feedback off
  set echo off
  set verify off

variable cd varchar2(10);
variable d number;

 declare
 ab varchar2(10) := 'Raj';
 a number := 10;
 c number;
 begin
 c := a+10;
 select ab,c into :cd,:d from dual;
 end;

 SPOOL 
 select :cd,:d from dual;
 SPOOL OFF
 EXIT;

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.

But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:

The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, including Limit Ad Tracking.

Including Limit Ad Tracking. This is what the last box is all about. So you must check the that box if you use AdMob. If you use other SDK I strongly recommend checking if they respect the guidelines as well.

Since I run only ads (Google AdMob), I checked the first (Serve ads...) and last box (I, ___, confirm...). App was approved and released, no issues.

Source: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk

Round number to nearest integer

Your solution is calling round without specifying the second argument (number of decimal places)

>>> round(0.44)
0
>>> round(0.64)
1

which is a much better result than

>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0

From the Python documentation at https://docs.python.org/3/library/functions.html#round

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

How does one output bold text in Bash?

I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.

First, turn on support for special characters in echo, using -e option. Later, use ansi escape sequence ESC[1m, like:

echo -e "\033[1mSome Text"

More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php

Is it possible to delete an object's property in PHP?

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.

How can I copy the output of a command directly into my clipboard?

I always wanted to do this and found a nice and easy way of doing it. I wrote down the complete procedure just in case anyone else needs it.

First install a 16 kB program called xclip:

sudo apt-get install xclip

You can then pipe the output into xclip to be copied into the clipboard:

cat file | xclip

To paste the text you just copied, you shall use:

xclip -o

To simplify life, you can set up an alias in your .bashrc file as I did:

alias "c=xclip"
alias "v=xclip -o"

To see how useful this is, imagine I want to open my current path in a new terminal window (there may be other ways of doing it like Ctrl+T on some systems, but this is just for illustration purposes):

Terminal 1:
pwd | c

Terminal 2:
cd `v`

Notice the ` ` around v. This executes v as a command first and then substitutes it in-place for cd to use.

Only copy the content to the X clipboard

cat file | xclip

If you want to paste somewhere else other than a X application, try this one:

cat file | xclip -selection clipboard

Execute CMD command from code

How about you creat a batch file with the command you want, and call it with Process.Start

dir.bat content:

dir

then call:

Process.Start("dir.bat");

Will call the bat file and execute the dir

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

I won't stress much on the difference as it is already covered, but notice the below:

  • android:backgroundTint android:backgroundTintMode are only available at API 21
  • If you have a widget that has a png/vector drawable background set by android:background, and you want to change its default color, then you can use android:backgroundTint to add a shade to it.

example

<Button
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_dialog_email" />

enter image description here

<Button
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_dialog_email"
    android:backgroundTint="@color/colorAccent" />

enter image description here

Another example

If you try to change the accent color of the FloatingActionButton using android:background you won't notice a change, that is because it's already utilizes app:srcCompat, so in order to do that you can use android:backgroundTint instead

What is the difference between Trap and Interrupt?

A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap.

Android: How to open a specific folder via Intent and show its content in a file browser?

This should work:

Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");

if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
    startActivity(intent);
}
else
{
    // if you reach this place, it means there is no any file 
    // explorer app installed on your device
}

Please, be sure that you have any file explorer app installed on your device.

EDIT: added a shantanu's recommendation from the comment.

LIBRARIES: You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.

Git keeps prompting me for a password

This happened to me when I upgraded to macOS v10.12 (Sierra). Looks like the SSH agent got cleared upon upgrade.

$ ssh-add -L
The agent has no identities.

Simply running ssh-add located my existing identity. I entered the password and was good to go again.

Can typescript export a function?

It's hard to tell what you're going for in that example. exports = is about exporting from external modules, but the code sample you linked is an internal module.

Rule of thumb: If you write module foo { ... }, you're writing an internal module; if you write export something something at top-level in a file, you're writing an external module. It's somewhat rare that you'd actually write export module foo at top-level (since then you'd be double-nesting the name), and it's even rarer that you'd write module foo in a file that had a top-level export (since foo would not be externally visible).

The following things make sense (each scenario delineated by a horizontal rule):


// An internal module named SayHi with an exported function 'foo'
module SayHi {
    export function foo() {
       console.log("Hi");
    }

    export class bar { }
}

// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();

file1.ts

// This *file* is an external module because it has a top-level 'export'
export function foo() {
    console.log('hi');
}

export class bar { }

file2.ts

// This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();

file1.ts

// This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };

file2.ts

// This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g

Format a Go string without printing?

1. Simple strings

For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf() and friends (fmt.Sprint(), fmt.Sprintln()). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the result as a string instead of printing them to the standard output.

For example:

s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)

The variable s will be initialized with the value:

Hi, my name is Bob and I'm 23 years old.

Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf() (which requires a format string) as Sprint() does exactly this. See this example:

i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"

For concatenating only strings, you may also use strings.Join() where you can specify a custom separator string (to be placed between the strings to join).

Try these on the Go Playground.

2. Complex strings (documents)

If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf() becomes less readable and less efficient (especially if you have to do this many times).

For this the standard library provides the packages text/template and html/template. These packages implement data-driven templates for generating textual output. html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.

Using the template packages basically requires you to provide a static template in the form of a string value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.

You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are structs and map values which may be nested.

Example:

For example let's say you want to generate email messages that look like this:

Hi [name]!

Your account is ready, your user name is: [user-name]

You have the following roles assigned:
[role#1], [role#2], ... [role#n]

To generate email message bodies like this, you could use the following static template:

const emailTmpl = `Hi {{.Name}}!

Your account is ready, your user name is: {{.UserName}}

You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`

And provide data like this for executing it:

data := map[string]interface{}{
    "Name":     "Bob",
    "UserName": "bob92",
    "Roles":    []string{"dbteam", "uiteam", "tester"},
}

Normally output of templates are written to an io.Writer, so if you want the result as a string, create and write to a bytes.Buffer (which implements io.Writer). Executing the template and getting the result as string:

t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
    panic(err)
}
s := buf.String()

This will result in the expected output:

Hi Bob!

Your account is ready, your user name is: bob92

You have the following roles assigned:
dbteam, uiteam, tester

Try it on the Go Playground.

Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer which is: strings.Builder. Usage is very similar:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    panic(err)
}
s := builder.String()

Try this one on the Go Playground.

Note: you may also display the result of a template execution if you provide os.Stdout as the target (which also implements io.Writer):

t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
    panic(err)
}

This will write the result directly to os.Stdout. Try this on the Go Playground.

Mongodb: failed to connect to server on first connect

To connect to mongodb with mongoose, you can use :

mongoose.connect('mongodb://localhost/users_test');

or

mongoose.connect('localhost/users_test');

or

mongoose.connect('localhost','users_test');

But not mongoose.connect('mongodb:localhost/users_test');, it doesnt match the right hostname (mongodb instead of localhost)

Avoid printStackTrace(); use a logger call instead

In Simple,e.printStackTrace() is not good practice,because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes.

restrict edittext to single line

Using android:singleLine="true" is deprecated.

Just add your input type and set maxline to 1 and everything will work fine

android:inputType="text"
android:maxLines="1"

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Here's an example

// in the service
getVehicles(){
    return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
}

// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
    this.vehicles = this._vehicleService.getVehicles();
}

// in template
<div *ngFor='let vehicle of vehicles | async'>
    {{vehicle.name}}
</div>

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

You can reverse the logic. Instead of deleting an invalid row after it has been inserted, write an INSTEAD OF trigger to insert only if you verify the row is valid.

CREATE TRIGGER mytrigger ON sometable
INSTEAD OF INSERT
AS BEGIN
  DECLARE @isnum TINYINT;

  SELECT @isnum = ISNUMERIC(somefield) FROM inserted;

  IF (@isnum = 1)
    INSERT INTO sometable SELECT * FROM inserted;
  ELSE
    RAISERROR('somefield must be numeric', 16, 1)
      WITH SETERROR;
END

If your application doesn't want to handle errors (as Joel says is the case in his app), then don't RAISERROR. Just make the trigger silently not do an insert that isn't valid.

I ran this on SQL Server Express 2005 and it works. Note that INSTEAD OF triggers do not cause recursion if you insert into the same table for which the trigger is defined.

What does the line "#!/bin/sh" mean in a UNIX shell script?

#!/bin/sh or #!/bin/bash has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh then it will consider all commands as a one script and it will show the that this file is running in ps command and not the commands inside the file.

./echo.sh

ps -ef |grep echo
trainee   3036  2717  0 16:24 pts/0    00:00:00 /bin/sh ./echo.sh
root      3042  2912  0 16:24 pts/1    00:00:00 grep --color=auto echo

Removing viewcontrollers from navigation stack

Details

  • Swift 5.1, Xcode 11.3.1

Solution

extension UIViewController {
    func removeFromNavigationController() { navigationController?.removeController(.last) { self == $0 } }
}

extension UINavigationController {
    enum ViewControllerPosition { case first, last }
    enum ViewControllersGroupPosition { case first, last, all }

    func removeController(_ position: ViewControllerPosition, animated: Bool = true,
                          where closure: (UIViewController) -> Bool) {
        var index: Int?
        switch position {
            case .first: index = viewControllers.firstIndex(where: closure)
            case .last: index = viewControllers.lastIndex(where: closure)
        }
        if let index = index { removeControllers(animated: animated, in: Range(index...index)) }
    }

    func removeControllers(_ position: ViewControllersGroupPosition, animated: Bool = true,
                           where closure: (UIViewController) -> Bool) {
        var range: Range<Int>?
        switch position {
            case .first: range = viewControllers.firstRange(where: closure)
            case .last:
                guard let _range = viewControllers.reversed().firstRange(where: closure) else { return }
                let count = viewControllers.count - 1
                range = .init(uncheckedBounds: (lower: count - _range.min()!, upper: count - _range.max()!))
            case .all:
                let viewControllers = self.viewControllers.filter { !closure($0) }
                setViewControllers(viewControllers, animated: animated)
                return
        }
        if let range = range { removeControllers(animated: animated, in: range) }
    }

    func removeControllers(animated: Bool = true, in range: Range<Int>) {
        var viewControllers = self.viewControllers
        viewControllers.removeSubrange(range)
        setViewControllers(viewControllers, animated: animated)
    }

    func removeControllers(animated: Bool = true, in range: ClosedRange<Int>) {
        removeControllers(animated: animated, in: Range(range))
    }
}

private extension Array {
    func firstRange(where closure: (Element) -> Bool) -> Range<Int>? {
        guard var index = firstIndex(where: closure) else { return nil }
        var indexes = [Int]()
        while index < count && closure(self[index]) {
            indexes.append(index)
            index += 1
        }
        if indexes.isEmpty { return nil }
        return Range<Int>(indexes.min()!...indexes.max()!)
    }
}

Usage

removeFromParent()

navigationController?.removeControllers(in: 1...3)

navigationController?.removeController(.first) { $0 != self }

navigationController?.removeController(.last) { $0 != self }

navigationController?.removeControllers(.all) { $0.isKind(of: ViewController.self) }

navigationController?.removeControllers(.first) { !$0.isKind(of: ViewController.self) }

navigationController?.removeControllers(.last) { $0 != self }

Full Sample

Do not forget to paste here the solution code

import UIKit

class ViewController2: ViewController {}

class ViewController: UIViewController {

    private var tag: Int = 0
    deinit { print("____ DEINITED: \(self), tag: \(tag)" ) }

    override func viewDidLoad() {
        super.viewDidLoad()
        print("____ INITED: \(self)")
        let stackView = UIStackView()
        stackView.axis = .vertical
        view.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        stackView.addArrangedSubview(createButton(text: "Push ViewController() white", selector: #selector(pushWhiteViewController)))
        stackView.addArrangedSubview(createButton(text: "Push ViewController() gray", selector: #selector(pushGrayViewController)))
        stackView.addArrangedSubview(createButton(text: "Push ViewController2() green", selector: #selector(pushController2)))
        stackView.addArrangedSubview(createButton(text: "Push & remove previous VC", selector: #selector(pushViewControllerAndRemovePrevious)))
        stackView.addArrangedSubview(createButton(text: "Remove first gray VC", selector: #selector(dropFirstGrayViewController)))
        stackView.addArrangedSubview(createButton(text: "Remove last gray VC", selector: #selector(dropLastGrayViewController)))
        stackView.addArrangedSubview(createButton(text: "Remove all gray VCs", selector: #selector(removeAllGrayViewControllers)))
        stackView.addArrangedSubview(createButton(text: "Remove all VCs exept Last", selector: #selector(removeAllViewControllersExeptLast)))
        stackView.addArrangedSubview(createButton(text: "Remove all exept first and last VCs", selector: #selector(removeAllViewControllersExeptFirstAndLast)))
        stackView.addArrangedSubview(createButton(text: "Remove all ViewController2()", selector: #selector(removeAllViewControllers2)))
        stackView.addArrangedSubview(createButton(text: "Remove first VCs where bg != .gray", selector: #selector(dropFirstViewControllers)))
        stackView.addArrangedSubview(createButton(text: "Remove last VCs where bg == .gray", selector: #selector(dropLastViewControllers)))
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if title?.isEmpty ?? true { title = "First" }
    }

    private func createButton(text: String, selector: Selector) -> UIButton {
        let button = UIButton()
        button.setTitle(text, for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: selector, for: .touchUpInside)
        return button
    }
}

extension ViewController {

    private func createViewController<VC: ViewController>(backgroundColor: UIColor = .white) -> VC {
        let viewController = VC()
        let counter = (navigationController?.viewControllers.count ?? -1 ) + 1
        viewController.tag = counter
        viewController.title = "Controller \(counter)"
        viewController.view.backgroundColor = backgroundColor
        return viewController
    }

    @objc func pushWhiteViewController() {
        navigationController?.pushViewController(createViewController(), animated: true)
    }

    @objc func pushGrayViewController() {
        navigationController?.pushViewController(createViewController(backgroundColor: .lightGray), animated: true)
    }

    @objc func pushController2() {
        navigationController?.pushViewController(createViewController(backgroundColor: .green) as ViewController2, animated: true)
    }

    @objc func pushViewControllerAndRemovePrevious() {
        navigationController?.pushViewController(createViewController(), animated: true)
        removeFromNavigationController()
    }

    @objc func removeAllGrayViewControllers() {
        navigationController?.removeControllers(.all) { $0.view.backgroundColor == .lightGray }
    }

    @objc func removeAllViewControllersExeptLast() {
        navigationController?.removeControllers(.all) { $0 != self }
    }

    @objc func removeAllViewControllersExeptFirstAndLast() {
        guard let navigationController = navigationController, navigationController.viewControllers.count > 1 else { return }
        let lastIndex = navigationController.viewControllers.count - 1
        navigationController.removeControllers(in: 1..<lastIndex)
    }

    @objc func removeAllViewControllers2() {
        navigationController?.removeControllers(.all) { $0.isKind(of: ViewController2.self) }
    }

    @objc func dropFirstViewControllers() {
        navigationController?.removeControllers(.first) { $0.view.backgroundColor != .lightGray }
    }

    @objc func dropLastViewControllers() {
        navigationController?.removeControllers(.last) { $0.view.backgroundColor == .lightGray }
    }

    @objc func dropFirstGrayViewController() {
        navigationController?.removeController(.first) { $0.view.backgroundColor == .lightGray }
    }

    @objc func dropLastGrayViewController() {
        navigationController?.removeController(.last) { $0.view.backgroundColor == .lightGray }
    }
}

Result

enter image description here

css with background image without repeating the image

Try this

padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;

This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need...

Numpy: Divide each row by a vector element

As has been mentioned, slicing with None or with np.newaxes is a great way to do this. Another alternative is to use transposes and broadcasting, as in

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function. There really are a lot of ways to do this.

For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

How to send email via Django?

Late, but:

In addition to the DEFAULT_FROM_EMAIL fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.

I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I'm not totally sure if that's necessary but it can't hurt. You can do that like so: ssh -D 8080 -fN <username>@<host>, then set your web browser to use localhost:8080 as a SOCKS proxy.

What does "both" mean in <div style="clear:both">

Description of the possible values:

  • left: No floating elements allowed on the left side
  • right: No floating elements allowed on the right side
  • both: No floating elements allowed on either the left or the right side
  • none: Default. Allows floating elements on both sides
  • inherit: Specifies that the value of the clear property should be inherited from the parent element

Source: w3schools.com

javascript object max size limit

you have to put this in web.config :

<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="50000000" />
      </webServices>
    </scripting>
  </system.web.extensions>

Get table column names in MySQL?

You may also want to check out mysql_fetch_array(), as in:

$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
//$row[0] = 'First Field';
//$row['first_field'] = 'First Field';
}

How to produce an csv output file from stored procedure in SQL Server

I have tried this and it is working fine for me:

sqlcmd -S servername -E -s~ -W -k1 -Q  "sql query here" > "\\file_path\file_name.csv"

'tsc command not found' in compiling typescript

You are all messing with the global installations and -path files. Just a little error might damage every project you have ever written, and you will spend the rest of the night trying to get a console.log('hi') to work again.

If you have run npm i typescript --save-dev in your project - just try to run:

npx tsc 

And see if it works before messing with global stuff (unless of course you really know what you are doing)

How to check what user php is running as?

add the file info.php to the following directory - your default http/apache directory - normally /var/www/html

with the following contents

<?php                                                                           
phpinfo();                                                                    
?>  

Then httpd/apache restart the go to your default html directory http://enter.server.here/info.php

would deliver the whole php pedigree!

Convert Date format into DD/MMM/YYYY format in SQL Server

There are already multiple answers and formatting types for SQL server 2008. But this method somewhat ambiguous and it would be difficult for you to remember the number with respect to Specific Date Format. That's why in next versions of SQL server there is better option.

If you are using SQL Server 2012 or above versions, you should use Format() function

FORMAT ( value, format [, culture ] )

With culture option, you can specify date as per your viewers.

DECLARE @d DATETIME = '10/01/2011';
SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result'
      ,FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English Result'
      ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'
      ,FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC) Result'; 
  
SELECT FORMAT ( @d, 'D', 'en-US' ) AS 'US English Result'
      ,FORMAT ( @d, 'D', 'en-gb' ) AS 'Great Britain English Result'
      ,FORMAT ( @d, 'D', 'de-de' ) AS 'German Result'
      ,FORMAT ( @d, 'D', 'zh-cn' ) AS 'Chinese (Simplified PRC) Result';

US English Result Great Britain English Result  German Result Simplified Chinese (PRC) Result
----------------  ----------------------------- ------------- -------------------------------------
10/1/2011         01/10/2011                    01.10.2011    2011/10/1

US English Result            Great Britain English Result  German Result                    Chinese (Simplified PRC) Result
---------------------------- ----------------------------- -----------------------------  ---------------------------------------
Saturday, October 01, 2011   01 October 2011               Samstag, 1. Oktober 2011        2011?10?1?
   

For OP's solution, we can use following format, which is already mentioned by @Martin Smith:

FORMAT(GETDATE(), 'dd/MMM/yyyy', 'en-us')

Some sample date formats:

enter image description here

If you want more date formats of SQL server, you should visit:

  1. Custom Date and Time Format
  2. Standard Date and Time Format

How to leave space in HTML

If you want to leave blank space in HTML while editing the website just use <br /> and copy-paste it under the last one and keep going like that until you have enough space. Hope it helps.

Keep background image fixed during scroll using css

background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}

Select objects based on value of variable in object using jq

Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

@Autowired - No qualifying bean of type found for dependency at least 1 bean

@Service: It tells that particular class is a Service to the client. Service class contains mainly business Logic. If you have more Service classes in a package than provide @Qualifier otherwise it should not require @Qualifier.

Case 1:

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
}

Case2:

@Service
public class EmployeeServiceImpl implements EmployeeService{
}

both cases are working...

Converting a string to an integer on Android

The much simpler method is to use the decode method of Integer so for example:

int helloInt = Integer.decode(hello);

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

exception in initializer error in java when using Netbeans

Make sure the project does not have any errors. Delete the project from workspace(make the workspace a different directory from the git folder) and import again.

How to determine if one array contains all elements of another array

This can be achieved by doing

(a2 & a1) == a2

This creates the intersection of both arrays, returning all elements from a2 which are also in a1. If the result is the same as a2, you can be sure you have all elements included in a1.

This approach only works if all elements in a2 are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

PHP: Get key from array?

Use the array_search function.

Example from php.net

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

How can I get npm start at a different directory?

This one-liner should work too:

(cd /path/to/your/app && npm start)

Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:

(cd /path/to/your/app && npm start && cd -)

I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.

Can you split a stream into two streams?

Shorter version that uses Lombok

import java.util.function.Consumer;
import java.util.function.Predicate;

import lombok.RequiredArgsConstructor;

/**
 * Forks a Stream using a Predicate into postive and negative outcomes.
 */
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PROTECTED)
public class StreamForkerUtil<T> implements Consumer<T> {
    Predicate<T> predicate;
    Consumer<T> positiveConsumer;
    Consumer<T> negativeConsumer;

    @Override
    public void accept(T t) {
        (predicate.test(t) ? positiveConsumer : negativeConsumer).accept(t);
    }
}

How to force a list to be vertical using html css

Try putting display: block in the <li> tags instead of the <ul>

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:

SELECT * FROM match WHERE id NOT IN 
    ( SELECT id FROM email WHERE id IS NOT NULL) ;

SELECT
    m.*
FROM
    match m
    LEFT OUTER JOIN email e ON
        m.id = e.id
        AND e.id IS NOT NULL
WHERE
    e.id IS NULL

The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.

Android WebView Cookie Problem

I magically solved all my cookie problems with this one line in onCreate:

CookieHandler.setDefault(new CookieManager());

edit: it stopped working today. :( what the crap, android.

How to change font in ipython notebook

In addition to the suggestion by Konrad here, I'd like to suggest jupyter themes, which seems to have more options, such as line-height, font size, cell width etc.

Command line usage:

jt  [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT]
[-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE]
[-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim]
[-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N]
[-r] [-dfonts]

How can I remove a substring from a given String?

If you know the start and end index you may use this

string = string.substring(0, start_index) + string.substring(end_index, string.length());

How correctly produce JSON by RESTful web service?

@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
    return jsonObject;
}       

How do I iterate over a range of numbers defined by variables in Bash?

discussion

Using seq is fine, as Jiaaro suggested. Pax Diablo suggested a Bash loop to avoid calling a subprocess, with the additional advantage of being more memory friendly if $END is too large. Zathrus spotted a typical bug in the loop implementation, and also hinted that since i is a text variable, continuous conversions to-and-fro numbers are performed with an associated slow-down.

integer arithmetic

This is an improved version of the Bash loop:

typeset -i i END
let END=5 i=1
while ((i<=END)); do
    echo $i
    …
    let i++
done

If the only thing that we want is the echo, then we could write echo $((i++)).

ephemient taught me something: Bash allows for ((expr;expr;expr)) constructs. Since I've never read the whole man page for Bash (like I've done with the Korn shell (ksh) man page, and that was a long time ago), I missed that.

So,

typeset -i i END # Let's be explicit
for ((i=1;i<=END;++i)); do echo $i; done

seems to be the most memory-efficient way (it won't be necessary to allocate memory to consume seq's output, which could be a problem if END is very large), although probably not the “fastest”.

the initial question

eschercycle noted that the {a..b} Bash notation works only with literals; true, accordingly to the Bash manual. One can overcome this obstacle with a single (internal) fork() without an exec() (as is the case with calling seq, which being another image requires a fork+exec):

for i in $(eval echo "{1..$END}"); do

Both eval and echo are Bash builtins, but a fork() is required for the command substitution (the $(…) construct).

Adding a module (Specifically pymorph) to Spyder (Python IDE)

One can also follow the below steps : Spyder -> Tools -> Open Command Prompt -> write the command "pip install html5lib"

Image UriSource and Data Binding

The problem with the answer that was chosen here is that when navigating back and forth, the converter will get triggered every time the page is shown.

This causes new file handles to be created continuously and will block any attempt to delete the file because it is still in use. This can be verified by using Process Explorer.

If the image file might be deleted at some point, a converter such as this might be used: using XAML to bind to a System.Drawing.Image into a System.Windows.Image control

The disadvantage with this memory stream method is that the image(s) get loaded and decoded every time and no caching can take place: "To prevent images from being decoded more than once, assign the Image.Source property from an Uri rather than using memory streams" Source: "Performance tips for Windows Store apps using XAML"

To solve the performance issue, the repository pattern can be used to provide a caching layer. The caching could take place in memory, which may cause memory issues, or as thumbnail files that reside in a temp folder that can be cleared when the app exits.

jQuery autocomplete with callback ajax json

My issue was that end users would start typing in a textbox and receive autocomplete (ACP) suggestions and update the calling control if a suggestion was selected as the ACP is designed by default. However, I also needed to update multiple other controls (textboxes, DropDowns, etc...) with data specific to the end user's selection. I have been trying to figure out an elegant solution to the issue and I feel the one I developed is worth sharing and hopefully will save you at least some time.

WebMethod (SampleWM.aspx):

  • PURPOSE:

    • To capture SQL Server Stored Procedure results and return them as a JSON String to the AJAX Caller
  • NOTES:

    • Data.GetDataTableFromSP() - Is a custom function that returns a DataTable from the results of a Stored Procedure
    • < System.Web.Services.WebMethod(EnableSession:=True) > _
    • Public Shared Function GetAutoCompleteData(ByVal QueryFilterAs String) As String

 //Call to custom function to return SP results as a DataTable
 // DataTable will consist of Field0 - Field5
 Dim params As ArrayList = New ArrayList
 params.Add("@QueryFilter|" & QueryFilter)
 Dim dt As DataTable = Data.GetDataTableFromSP("AutoComplete", params, [ConnStr])

 //Create a StringBuilder Obj to hold the JSON 
 //IE: [{"Field0":"0","Field1":"Test","Field2":"Jason","Field3":"Smith","Field4":"32","Field5":"888-555-1212"},{"Field0":"1","Field1":"Test2","Field2":"Jane","Field3":"Doe","Field4":"25","Field5":"888-555-1414"}]
 Dim jStr As StringBuilder = New StringBuilder

 //Loop the DataTable and convert row into JSON String
 If dt.Rows.Count > 0 Then
      jStr.Append("[")
      Dim RowCnt As Integer = 1
      For Each r As DataRow In dt.Rows
           jStr.Append("{")
           Dim ColCnt As Integer = 0
           For Each c As DataColumn In dt.Columns
               If ColCnt = 0 Then
                   jStr.Append("""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
               Else
                   jStr.Append(",""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
                End If
                ColCnt += 1
            Next

            If Not RowCnt = dt.Rows.Count Then
                jStr.Append("},")
            Else
                jStr.Append("}")
            End If

            RowCnt += 1
        Next

        jStr.Append("]")
    End If

    //Return JSON to WebMethod Caller
    Return jStr.ToString

AutoComplete jQuery (AutoComplete.aspx):

  • PURPOSE:
    • Perform the Ajax Request to the WebMethod and then handle the response

    $(function() {
      $("#LookUp").autocomplete({                
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "SampleWM.aspx/GetAutoCompleteData",
                    dataType: "json",
                    data:'{QueryFilter: "' + request.term  + '"}',
                    success: function (data) {
                        response($.map($.parseJSON(data.d), function (item) {                                
                            var AC = new Object();

                            //autocomplete default values REQUIRED
                            AC.label = item.Field0;
                            AC.value = item.Field1;

                            //extend values
                            AC.FirstName = item.Field2;
                            AC.LastName = item.Field3;
                            AC.Age = item.Field4;
                            AC.Phone = item.Field5;

                            return AC
                        }));       
                    }                                             
                });
            },
            minLength: 3,
            select: function (event, ui) {                    
                $("#txtFirstName").val(ui.item.FirstName);
                $("#txtLastName").val(ui.item.LastName);
                $("#ddlAge").val(ui.item.Age);
                $("#txtPhone").val(ui.item.Phone);
             }                    
        });
     });

Adding integers to an int array

Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.

num[i] = s;
i++;

Setting Elastic search limit to "unlimited"

Another approach is to first do a searchType: 'count', then and then do a normal search with size set to results.count.

The advantage here is it avoids depending on a magic number for UPPER_BOUND as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan.

The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.

How to break lines in PowerShell?

You can also just use:

Write-Host "";

Or, to put it in terms of your specific question:

$str = ""
foreach($line in $file){
  if($line -Match $review){ #Special condition
    $str += Write-Host ""
    $str += ANSWER #looking for ANSWER
  }
  #code.....
}

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Since Spark 1.5 you can use a number of date processing functions:

import datetime
from pyspark.sql.functions import year, month, dayofmonth

elevDF = sc.parallelize([
    (datetime.datetime(1984, 1, 1, 0, 0), 1, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 2, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 3, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 4, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 5, 638.55)
]).toDF(["date", "hour", "value"])

elevDF.select(
    year("date").alias('year'), 
    month("date").alias('month'), 
    dayofmonth("date").alias('day')
).show()
# +----+-----+---+
# |year|month|day|
# +----+-----+---+
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# +----+-----+---+

You can use simple map as with any other RDD:

elevDF = sqlContext.createDataFrame(sc.parallelize([
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=1, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=2, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=3, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=4, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=5, value=638.55)]))

(elevDF
 .map(lambda (date, hour, value): (date.year, date.month, date.day))
 .collect())

and the result is:

[(1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1)]

Btw: datetime.datetime stores an hour anyway so keeping it separately seems to be a waste of memory.

How to remove illegal characters from path and filenames?

You can remove illegal chars using Linq like this:

var invalidChars = Path.GetInvalidFileNameChars();

var invalidCharsRemoved = stringWithInvalidChars
.Where(x => !invalidChars.Contains(x))
.ToArray();

EDIT
This is how it looks with the required edit mentioned in the comments:

var invalidChars = Path.GetInvalidFileNameChars();

string invalidCharsRemoved = new string(stringWithInvalidChars
  .Where(x => !invalidChars.Contains(x))
  .ToArray());

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

create table with sequence.nextval in oracle

In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:

E.g.,

CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
  id          NUMBER DEFAULT t1_seq.NEXTVAL,
  description VARCHAR2(30)
);

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Just to add to others, a note specific to forking.

It's good to realize that technically, cloning the repo and forking the repo are the same thing. Do:

git clone $some_other_repo

and you can tap yourself on the back---you have just forked some other repo.

Git, as a VCS, is in fact all about cloning forking. Apart from "just browsing" using remote UI such as cgit, there is very little to do with git repo that does not involve forking cloning the repo at some point.

However,

  • when someone says I forked repo X, they mean that they have created a clone of the repo somewhere else with intention to expose it to others, for example to show some experiments, or to apply different access control mechanism (eg. to allow people without Github access but with company internal account to collaborate).

    Facts that: the repo is most probably created with other command than git clone, that it's most probably hosted somewhere on a server as opposed to somebody's laptop, and most probably has slightly different format (it's a "bare repo", ie. without working tree) are all just technical details.

    The fact that it will most probably contain different set of branches, tags or commits is most probably the reason why they did it in the first place.

    (What Github does when you click "fork", is just cloning with added sugar: it clones the repo for you, puts it under your account, records the "forked from" somewhere, adds remote named "upstream", and most importantly, plays the nice animation.)

  • When someone says I cloned repo X, they mean that they have created a clone of the repo locally on their laptop or desktop with intention study it, play with it, contribute to it, or build something from source code in it.

The beauty of Git is that it makes this all perfectly fit together: all these repos share the common part of block commit chain so it's possible to safely (see note below) merge changes back and forth between all these repos as you see fit.


Note: "safely" as long as you don't rewrite the common part of the chain, and as long as the changes are not conflicting.

Display Animated GIF

Some thoughts on the BitmapDecode example... Basically it uses the ancient, but rather featureless Movie class from android.graphics. On recent API versions you need to turn off hardware acceleration, as described here. It was segfaulting for me otherwise.

<activity
            android:hardwareAccelerated="false"
            android:name="foo.GifActivity"
            android:label="The state of computer animation 2014">
</activity>

Here is the BitmapDecode example shortened with only the GIF part. You have to make your own Widget (View) and draw it by yourself. Not quite as powerful as an ImageView.

import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.*;
import android.view.View;

public class GifActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new GifView(this));
    }

    static class GifView extends View {
        Movie movie;

        GifView(Context context) {
            super(context);
            movie = Movie.decodeStream(
                    context.getResources().openRawResource(
                            R.drawable.some_gif));
        }
        @Override
        protected void onDraw(Canvas canvas) {   
            if (movie != null) {
                movie.setTime(
                    (int) SystemClock.uptimeMillis() % movie.duration());
                movie.draw(canvas, 0, 0);
                invalidate();
            }
        }
    }
}

2 other methods, one with ImageView another with WebView can be found in this fine tutorial. The ImageView method uses the Apache licensed android-gifview from Google Code.

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I get the same error in Chrome after pasting code copied from jsfiddle.

If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

ALTER table - adding AUTOINCREMENT in MySQL

The syntax:

   ALTER TABLE `table1` CHANGE `itemId` `itemId` INT( 11 ) NOT NULL AUTO_INCREMENT 

But the table needs a defined key (ex primary key on itemId).

HTML5 Audio stop function

Instead of stop() you could try with:

sound.pause();
sound.currentTime = 0;

This should have the desired effect.

How to print Unicode character in Python?

This fixes UTF-8 printing in python:

UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

The correct format should be

@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name 
public class FooBar{

How to move a git repository into another directory and make that directory a git repository?

It's even simpler than that. Just did this (on Windows, but it should work on other OS):

  1. Create newrepo.
  2. Move gitrepo1 into newrepo.
  3. Move .git from gitrepo1 to newrepo (up one level).
  4. Commit changes (fix tracking as required).

Git just sees you added a directory and renamed a bunch of files. No biggie.

Java for loop multiple variables

Your for loop is wrong. Try :

for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){

Also, System instead of system and == instead of ===.

But I'm not sure what you're trying to do.

Is there a Python Library that contains a list of all the ascii characters?

No, there isn't, but you can easily make one:

    #Your ascii.py program:
    def charlist(begin, end):
        charlist = []
        for i in range(begin, end):
            charlist.append(chr(i))
        return ''.join(charlist)

    #Python shell:
    #import ascii
    #print(ascii.charlist(50, 100))
    #Comes out as:

    #23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abc

Remove border from buttons

Add

padding: 0;
border: none;
background: none;

to your buttons.

Demo:

https://jsfiddle.net/Vestride/dkr9b/

ExecJS and could not find a JavaScript runtime

Just add ExecJS and the Ruby Racer in your gem file and run bundle install after.

gem 'execjs'

gem 'therubyracer'

Everything should be fine after.

Error while installing json gem 'mkmf.rb can't find header files for ruby'

For Ubuntu 18, after checking log file mentioned while install

Results logged to /var/canvas/vendor/bundle/ruby/2.5.0/extensions/x86_64-linux/2.5.0/nio4r-2.5.2/gem_make.out

with

less /var/canvas/vendor/bundle/ruby/2.5.0/extensions/x86_64-linux/2.5.0/nio4r-2.5.2/gem_make.out

I noticed that make is not found. So installed make by

sudo apt-get install make

everything worked.

"Actual or formal argument lists differs in length"

Say you have defined your class like this:

    @Data
    @AllArgsConstructor(staticName = "of")
    private class Pair<P,Q> {

        public P first;
        public Q second;
    }

So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

Pair<Integer, String> pair = Pair.of(menuItemId, category);

If you define it like this, you will get the error asked for.

Pair<Integer, String> pair = new Pair(menuItemId, category);

Loop through JSON object List

This will work!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

How to create an Array with AngularJS's ng-model

It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.telephone = []; // << remember to set this
}]);

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

MySQL - Operand should contain 1 column(s)

In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:

SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;

And has to be:

SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;

Sounds silly, but it was causing this error and it took some time to figure it out.

Codeigniter unset session

I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session.

session_unset();
session_destroy();

Values of disabled inputs will not be submitted

You can use three things to mimic disabled:

  1. HTML: readonly attribute (so that the value present in input can be used on form submission. Also the user can't change the input value)

  2. CSS: 'pointer-events':'none' (blocking the user from clicking the input)

  3. HTML: tabindex="-1" (blocking the user to navigate to the input from the keyboard)

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Android OnClickListener - identify a button

The best way is by switch-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:

if (b1 == v) {
 // ...
} else if (b2 == v) {

I don't know exactly why they chose this way, but it works too.

How can I extract all values from a dictionary in Python?

If you want all of the values, use this:

dict_name_goes_here.values()

Trim spaces from end of a NSString

To remove whitespace from only the beginning and end of a string in Swift:

Swift 3

string.trimmingCharacters(in: .whitespacesAndNewlines)

Previous Swift Versions

string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))

Alternative for PHP_excel

For Writing Excel

  • PEAR's PHP_Excel_Writer (xls only)
  • php_writeexcel from Bettina Attack (xls only)
  • XLS File Generator commercial and xls only
  • Excel Writer for PHP from Sourceforge (spreadsheetML only)
  • Ilia Alshanetsky's Excel extension now on github (xls and xlsx, and requires commercial libXL component)
  • PHP's COM extension (requires a COM enabled spreadsheet program such as MS Excel or OpenOffice Calc running on the server)
  • The Open Office alternative to COM (PUNO) (requires Open Office installed on the server with Java support enabled)
  • PHP-Export-Data by Eli Dickinson (Writes SpreadsheetML - the Excel 2003 XML format, and CSV)
  • Oliver Schwarz's php-excel (SpreadsheetML)
  • Oliver Schwarz's original version of php-excel (SpreadsheetML)
  • excel_xml (SpreadsheetML, despite its name)... link reported as broken
  • The tiny-but-strong (tbs) project includes the OpenTBS tool for creating OfficeOpenXML documents (OpenDocument and OfficeOpenXML formats)
  • SimpleExcel Claims to read and write Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats
  • KoolGrid xls spreadsheets only, but also doc and pdf
  • PHP_XLSXWriter OfficeOpenXML
  • PHP_XLSXWriter_plus OfficeOpenXML, fork of PHP_XLSXWriter
  • php_writeexcel xls only (looks like it's based on PEAR SEW)
  • spout OfficeOpenXML (xlsx) and CSV
  • Slamdunk/php-excel (xls only) looks like an updated version of the old PEAR Spreadsheet Writer

For Reading Excel

A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.

All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.

Python convert set to string and vice versa

The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !

let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.

If interested to serialize you can use:

json.dumps  -> serialize
json.loads  -> deserialize

If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)

String to Set

set('abca')

Set to String

''.join(some_var_set)

example:

def test():
    some_var_set=set('abca')
    print("here is the set:",some_var_set,type(some_var_set))
    some_var_string=''.join(some_var_set)    
    print("here is the string:",some_var_string,type(some_var_string))

test()

How to get just numeric part of CSS property with jQuery?

use

$(this).cssUnit('marginBottom');

which return an array. first index returns margin bottom's value(example 20 for 20px) and second index returns margin bottom's unit(example px for 20px)

compare differences between two tables in mysql

I found another solution in this link

SELECT MIN (tbl_name) AS tbl_name, PK, column_list
FROM
 (
  SELECT ' source_table ' as tbl_name, S.PK, S.column_list
  FROM source_table AS S
  UNION ALL
  SELECT 'destination_table' as tbl_name, D.PK, D.column_list
  FROM destination_table AS D 
)  AS alias_table
GROUP BY PK, column_list
HAVING COUNT(*) = 1
ORDER BY PK

Login failed for user 'DOMAIN\MACHINENAME$'

  1. Change the App Pool Identity to Local System
  2. On SQL Mgmt > Security > Logins
    1. Find NT AUTHORITY\SYSTEM double click
    2. User Mappings > Check your database and give it a role below.
    3. Remember also to create the user data base o security logins with a correct password.

sqlplus how to find details of the currently connected database session

Take a look at this one (c) Tanel Poder. You may either run it from your glogin.sql (so these settings will update each time you connect, or just run it manually. Notice host title command - it changes your sql*plus console window title with session information - extremely useful with many windows open simultaneously.

-- the Who am I script

def   mysid="NA"
def _i_spid="NA"
def _i_cpid="NA"
def _i_opid="NA"
def _i_serial="NA"
def _i_inst="NA"
def _i_host="NA"
def _i_user="&_user"
def _i_conn="&_connect_identifier"

col i_username head USERNAME for a20
col i_sid head SID for a5 new_value mysid
col i_serial head SERIAL# for a8 new_value _i_serial
col i_cpid head CPID for a15 new_value _i_cpid
col i_spid head SPID for a15 new_value _i_spid
col i_opid head OPID for a5 new_value _i_opid
col i_host_name head HOST_NAME for a25 new_value _i_host
col i_instance_name head INST_NAME for a12 new_value _i_inst
col i_ver head VERSION for a10
col i_startup_day head STARTED for a8
col _i_user noprint new_value _i_user
col _i_conn noprint new_value _i_conn
col i_myoraver noprint new_value myoraver

select 
    s.username          i_username, 
    i.instance_name i_instance_name, 
    i.host_name         i_host_name, 
    to_char(s.sid)          i_sid, 
    to_char(s.serial#)      i_serial, 
    (select substr(banner, instr(banner, 'Release ')+8,10) from v$version where rownum = 1) i_ver,
    (select  substr(substr(banner, instr(banner, 'Release ')+8),
            1,
            instr(substr(banner, instr(banner, 'Release ')+8),'.')-1)
     from v$version 
     where rownum = 1) i_myoraver,
    to_char(startup_time, 'YYYYMMDD') i_startup_day, 
    p.spid              i_spid, 
    trim(to_char(p.pid))        i_opid, 
    s.process           i_cpid, 
    s.saddr             saddr, 
    p.addr              paddr,
    lower(s.username) "_i_user",
    upper('&_connect_identifier') "_i_conn"
from 
    v$session s, 
    v$instance i, 
    v$process p
where 
    s.paddr = p.addr
and 
    sid = (select sid from v$mystat where rownum = 1);

-- Windows CMD.exe specific stuff

-- host title %CP% &_i_user@&_i_conn [sid=&mysid ser#=&_i_serial spid=&_i_spid inst=&_i_inst host=&_i_host cpid=&_i_cpid opid=&_i_opid]
   host title %CP% &_i_user@&_i_conn [sid=&mysid #=&_i_serial]
-- host doskey /exename=sqlplus.exe desc=set lines 80 sqlprompt ""$Tdescribe $*$Tset lines 299 sqlprompt "SQL> "

-- short xterm title
-- host echo -ne "\033]0;&_i_user@&_i_inst &mysid[&_i_spid]\007"
-- long xterm title
--host echo -ne "\033]0;host=&_i_host inst=&_i_inst sid=&mysid ser#=&_i_serial spid=&_i_spid cpid=&_i_cpid opid=&_i_opid\007"


def myopid=&_i_opid
def myspid=&_i_spid
def mycpid=&_i_cpid

-- undef _i_spid _i_inst _i_host _i_user _i_conn _i_cpid

Sample output:

17:39:35 SYSTEM@saz-dev> @sandbox
Connected.
18:29:02 SYSTEM@sandbox> @me

USERNAME             INST_NAME    HOST_NAME                 SID   SERIAL#  VERSION    STARTED  SPID            OPID  CPID            SADDR    PADDR
-------------------- ------------ ------------------------- ----- -------- ---------- -------- --------------- ----- --------------- -------- --------
SYSTEM               xe           OARS-SANDBOX              34    175      11.2.0.2.0 20130318 3348            30    6108:7776       6F549590 6FF51020

1 row selected.

Elapsed: 00:00:00.04

WPF Binding to parent DataContext

Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).

If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel

public class ThisViewModel : ViewModelBase
{
    TypeOfAncestorViewModel Parent { get; set; }
}

and bind against that directly instead.

<TextBox Text="{Binding Parent}" />

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

How to delete an SVN project from SVN repository

The correct sentence is: svnadmin deltify $PATH. do not forghet to delet the project or repository from the file svn-acl (if you use it). if you simply delete the folder of repository you may corrupt the svn directory depending on how your svn is configured in your environment.

How to set the 'selected option' of a select dropdown list with jquery

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

Uncaught ReferenceError: $ is not defined error in jQuery

Scripts are loaded in the order you have defined them in the HTML.

Therefore if you first load:

<script type="text/javascript" src="./javascript.js"></script>

without loading jQuery first, then $ is not defined.

You need to first load jQuery so that you can use it.

I would also recommend placing your scripts at the bottom of your HTML for performance reasons.

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

For the most recent version Mojave version 10.14.1, I use

solved by downloaded from https://developer.apple.com/download/more/ " login by apple id, and download

Command line tool newest stable version.dmg

That makes everything work

the old answer

xcode-select --install

doesn't work for me.

Equivalent of Oracle's RowID in SQL Server

I took this example from MS SQL example and you can see the @ID can be interchanged with integer or varchar or whatever. This was the same solution I was looking for, so I am sharing it. Enjoy!!

-- UPDATE statement with CTE references that are correctly matched.
DECLARE @x TABLE (ID int, Stad int, Value int, ison bit);
INSERT @x VALUES (1, 0, 10, 0), (2, 1, 20, 0), (6, 0, 40, 0), (4, 1, 50, 0), (5, 3, 60, 0), (9, 6, 20, 0), (7, 5, 10, 0), (8, 8, 220, 0);
DECLARE @Error int;
DECLARE @id int;

WITH cte AS (SELECT top 1 * FROM @x WHERE Stad=6)
UPDATE x -- cte is referenced by the alias.
SET ison=1, @id=x.ID
FROM cte AS x

SELECT *, @id as 'random' from @x
GO

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

<bindings>
    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>

Syntax: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.administration.binding.bindinginformation?view=iis-dotnet

Format bytes to kilobytes, megabytes, gigabytes

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    // Uncomment one of the following alternatives
    // $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

(Taken from php.net, there are many other examples there, but I like this one best :-)

How can I print using JQuery

Hey If you want to print selected area or div ,Try This.

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>

Hope it helps you

Should I use SVN or Git?

There is an interesting Video on YouTube about this. Its from Linus Torwalds himself: Goolge Tech Talk: Linus Torvalds on git

React js onClick can't pass value to method

I have added code for onclick event value pass to the method in two ways . 1 . using bind method 2. using arrow(=>) method . see the methods handlesort1 and handlesort

var HeaderRows  = React.createClass({
    getInitialState : function() {
      return ({
        defaultColumns : ["col1","col2","col2","col3","col4","col5" ],
        externalColumns : ["ecol1","ecol2","ecol2","ecol3","ecol4","ecol5" ],

      })
    },
    handleSort:  function(column,that) {
       console.log(column);
       alert(""+JSON.stringify(column));
    },
    handleSort1:  function(column) {
       console.log(column);
       alert(""+JSON.stringify(column));
    },
    render: function () {
        var that = this;
        return(
        <div>
            <div>Using bind method</div>
            {this.state.defaultColumns.map(function (column) {
                return (
                    <div value={column} style={{height : '40' }}onClick={that.handleSort.bind(that,column)} >{column}</div>
                );
            })}
            <div>Using Arrow method</div>

            {this.state.defaultColumns.map(function (column) {
                return (
                    <div value={column} style={{height : 40}} onClick={() => that.handleSort1(column)} >{column}</div>

                );
            })}
            {this.state.externalColumns.map(function (column) {
                // Multi dimension array - 0 is column name
                var externalColumnName = column;
                return (<div><span>{externalColumnName}</span></div>
                );
            })}

        </div>);
    }
});

Concatenate chars to form String in java

Try this:

 str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);

Output:

ice

Import data into Google Colaboratory

  1. You can mount to google drive by running following

    from google.colab import drive drive.mount('/content/drive')

  2. Afterwards For training copy data from gdrive to colab root folder.

!cp -r '/content/drive/My Drive/Project_data' '/content'

where first path is gdrive path and second is colab root folder.

This way training is faster for large data.

Rollback to last git commit

Caveat Emptor - Destructive commands ahead.

Mitigation - git reflog can save you if you need it.


1) UNDO local file changes and KEEP your last commit

git reset --hard

2) UNDO local file changes and REMOVE your last commit

git reset --hard HEAD^

3) KEEP local file changes and REMOVE your last commit

git reset --soft HEAD^

java Compare two dates

You can use:

date1.before(date2);

or:

date1.after(date2);

Get checkbox value in jQuery

To get the value of the Value attribute you can do something like this:

$("input[type='checkbox']").val();

Or if you have set a class or id for it, you can:

$('#check_id').val();
$('.check_class').val();

However this will return the same value whether it is checked or not, this can be confusing as it is different to the submitted form behaviour.

To check whether it is checked or not, do:

if ($('#check_id').is(":checked"))
{
  // it is checked
}

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

Read whole ASCII file into C++ std::string

Try one of these two methods:

string get_file_string(){
    std::ifstream ifs("path_to_file");
    return string((std::istreambuf_iterator<char>(ifs)),
                  (std::istreambuf_iterator<char>()));
}

string get_file_string2(){
    ifstream inFile;
    inFile.open("path_to_file");//open the input file

    stringstream strStream;
    strStream << inFile.rdbuf();//read the file
    return strStream.str();//str holds the content of the file
}

Does a foreign key automatically create an index?

In PostgeSql you can check for indexes yourself if you hit \d tablename

You will see that btree indexes have been automatically created on columns with primary key and unique constraints, but not on columns with foreign keys.

I think that answers your question at least for postgres.

What is a regex to match ONLY an empty string?

Try looking here: https://docs.python.org/2/library/re.html

I ran into the same problem you had though. I could only build a regex that would match only the empty string and also "\n". Try trimming/replacing the newline characters in the string with another character first.

I was using http://pythex.org/ and trying weird regexes like these:

()

(?:)

^$

^(?:^\n){0}$

and so on.

How get sound input from microphone in python, and process it on the fly?

...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?

If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:

  • what is the "short-term" amplitude measurement
  • what is the delta increase you look for
  • how quickly the delta change must occur

Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.

How to capitalize the first character of each word in a string

package corejava.string.intern;

import java.io.DataInputStream;

import java.util.ArrayList;

/*
 * wap to accept only 3 sentences and convert first character of each word into upper case
 */

public class Accept3Lines_FirstCharUppercase {

    static String line;
    static String words[];
    static ArrayList<String> list=new ArrayList<String>();

    /**
     * @param args
     */
    public static void main(String[] args) throws java.lang.Exception{

        DataInputStream read=new DataInputStream(System.in);
        System.out.println("Enter only three sentences");
        int i=0;
        while((line=read.readLine())!=null){
            method(line);       //main logic of the code
            if((i++)==2){
                break;
            }
        }
        display();
        System.out.println("\n End of the program");

    }

    /*
     * this will display all the elements in an array
     */
    public static void display(){
        for(String display:list){
            System.out.println(display);
        }
    }

    /*
     * this divide the line of string into words 
     * and first char of the each word is converted to upper case
     * and to an array list
     */
    public static void method(String lineParam){
        words=line.split("\\s");
        for(String s:words){
            String result=s.substring(0,1).toUpperCase()+s.substring(1);
            list.add(result);
        }
    }

}

How to get the Google Map based on Latitude on Longitude?

Firstly add a div with id.

<div id="my_map_add" style="width:100%;height:300px;"></div>

<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>

Best way to unselect a <select> in jQuery?

$("#selectID option:selected").each(function(){
  $(this).removeAttr("selected");
});

This would iterate through each item and unselect only the ones which are checked

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

How can I run a html file from terminal?

Skip reading the html and use curl to POST whatever form data you want to submit to the server.

Handle spring security authentication exceptions with @ExceptionHandler

Taking answers from @Nicola and @Victor Wing and adding a more standardized way:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UnauthorizedErrorAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {

    private HttpMessageConverter messageConverter;

    @SuppressWarnings("unchecked")
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        MyGenericError error = new MyGenericError();
        error.setDescription(exception.getMessage());

        ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
        outputMessage.setStatusCode(HttpStatus.UNAUTHORIZED);

        messageConverter.write(error, null, outputMessage);
    }

    public void setMessageConverter(HttpMessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        if (messageConverter == null) {
            throw new IllegalArgumentException("Property 'messageConverter' is required");
        }
    }

}

Now, you can inject configured Jackson, Jaxb or whatever you use to convert response bodies on your MVC annotation or XML based configuration with its serializers, deserializers and so on.

Xcode/Simulator: How to run older iOS version?

If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.

You can still run the simulator from 3.2 onwards after upgrading.

In the iPhone Simulator try selecting Hardware -> Version -> 3.2

Quickly reading very large tables as dataframes

An alternative is to use the vroom package. Now on CRAN. vroom doesn't load the entire file, it indexes where each record is located, and is read later when you use it.

Only pay for what you use.

See Introduction to vroom, Get started with vroom and the vroom benchmarks.

The basic overview is that the initial read of a huge file, will be much faster, and subsequent modifications to the data may be slightly slower. So depending on what your use is, it could be the best option.

See a simplified example from vroom benchmarks below, the key parts to see is the super fast read times, but slightly sower operations like aggregate etc..

package                 read    print   sample   filter  aggregate   total
read.delim              1m      21.5s   1ms      315ms   764ms       1m 22.6s
readr                   33.1s   90ms    2ms      202ms   825ms       34.2s
data.table              15.7s   13ms    1ms      129ms   394ms       16.3s
vroom (altrep) dplyr    1.7s    89ms    1.7s     1.3s    1.9s        6.7s

setTimeout / clearTimeout problems

You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

What is the best way to remove accents (normalize) in a Python unicode string?

Unidecode is the correct answer for this. It transliterates any unicode string into the closest possible representation in ascii text.

Example:

accented_string = u'Málaga'
# accented_string is of type 'unicode'
import unidecode
unaccented_string = unidecode.unidecode(accented_string)
# unaccented_string contains 'Malaga'and is of type 'str'

Howto? Parameters and LIKE statement SQL

Well, I'd go with:

 Dim cmd as New SqlCommand(
 "SELECT * FROM compliance_corner"_
  + " WHERE (body LIKE @query )"_ 
  + " OR (title LIKE @query)")

 cmd.Parameters.Add("@query", "%" +searchString +"%")

What's the best way to get the current URL in Spring MVC?

Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:

public static String makeUrl(HttpServletRequest request)
{
    return request.getRequestURL().toString() + "?" + request.getQueryString();
}

I don't know about a way to do this with any Spring MVC facilities.

If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

And then use this to get the request bound to the current Thread:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

How to reset the state of a Redux store?

Combining the approaches of Dan, Ryan and Rob, to account for keeping the router state and initializing everything else in the state tree, I ended up with this:

const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
    ...appReducer({}, {}),
    router: state && state.router || {}
  } : state, action);

JavaScript Object Id

Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

How to change the style of a DatePicker in android?

Create custom DatePickerDialog style:

<style name="AppTheme.DatePickerDialog" parent="Theme.MaterialComponents.Light.Dialog">
    <item name="android:colorAccent">@color/colorPrimary</item>
    <item name="android:colorControlActivated">@color/colorPrimaryDark</item>
    <item name="android:buttonBarPositiveButtonStyle">@style/AppTheme.Alert.Button.Positive</item>
    <item name="android:buttonBarNegativeButtonStyle">@style/AppTheme.Alert.Button.Negative</item>
    <item name="android:buttonBarNeutralButtonStyle">@style/AppTheme.Alert.Button.Neutral</item>
</style>

<style name="AppTheme.Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/buttonPositive</item>
</style>

<style name="AppTheme.Alert.Button.Negative" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/buttonNegative</item>
</style>

<style name="AppTheme.Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="android:textColor">@color/buttonNeutral</item>
</style>

Set custom datePickerDialogTheme style in app theme:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:datePickerDialogTheme">@style/AppTheme.DatePickerDialog</item>
</style>

Set theme programmatically on initialization like this:

val datetime = DatePickerDialog(this, R.style.AppTheme_DatePickerDialog)

Stop Visual Studio from mixing line endings in files

see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017

  1. If it does not exist, add a new file called .editorconfig for your project

  2. manipulate editor config to use your preferred behaviour.

I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig

# http://editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[*.tmpl.html]
indent_size = 4

[*.scss]
indent_size = 2 

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Return list using select new in LINQ

You cannot return anonymous types from a class... (Well, you can, but you have to cast them to object first and then use reflection at the other side to get the data out again) so you have to create a small class for the data to be contained within.

class ProjectNameAndId
{
    public string Name { get; set; }
    public string Id { get; set; }
}

Then in your LINQ statement:

select new ProjectNameAndId { Name = pro.ProjectName, Id = pro.ProjectId };

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

How do I generate random number for each row in a TSQL Select?

Answering the old question, but this answer has not been provided previously, and hopefully this will be useful for someone finding this results through a search engine.

With SQL Server 2008, a new function has been introduced, CRYPT_GEN_RANDOM(8), which uses CryptoAPI to produce a cryptographically strong random number, returned as VARBINARY(8000). Here's the documentation page: https://docs.microsoft.com/en-us/sql/t-sql/functions/crypt-gen-random-transact-sql

So to get a random number, you can simply call the function and cast it to the necessary type:

select CAST(CRYPT_GEN_RANDOM(8) AS bigint)

or to get a float between -1 and +1, you could do something like this:

select CAST(CRYPT_GEN_RANDOM(8) AS bigint) % 1000000000 / 1000000000.0

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

How to make fixed header table inside scrollable div?

None of the other examples provided worked in my case - e.g. header would not match table body content when scrolling. I found a much simpler and clean way, allowing you to setup the table the normal way, and without too much code.

Example:

_x000D_
_x000D_
.table-wrapper{
  overflow-y: scroll;
  height: 100px;
}

.table-wrapper th{
    position: sticky;
    top: 0;
    background-color: #FFF;
}
_x000D_
<div class="table-wrapper">
    <table>
        <thead>
            <tr>
                <th>Header 1</th>
                <th>Header 2</th>
                <th>Header 3</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
            <tr>
                <td>Text</td>
                <td>Text</td>
                <td>Text</td>
            </tr>
        </tbody>
    </table>
</div>
_x000D_
_x000D_
_x000D_

Thanks to https://algoart.fr/articles/css-table-fixed-header

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

Is it possible to change a UIButtons background color?

Per @EthanB suggestion and @karim making a back filled rectangle, I just created a category for the UIButton to achieve this.

Just drop in the Category code: https://github.com/zmonteca/UIButton-PLColor

Usage:

[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled];

Optional forStates to use:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

setup android on eclipse but don't know SDK directory

I found it in this location:

C:\Users\amitsinha02\AppData\Local\Android\sdk\platform-tools

How to get label text value form a html page?

Use innerText/textContent:

  var el = document.getElementById('*spaM4');
  console.log(el.innerText || el.textContent);

Fiddle: http://jsfiddle.net/NeTgC/2/

Unicode character for "X" cancel / close?

there's another one not mentioned here - nice thin - if you need that kind of look for your project: ╳

&#x2573; or decimal: &#9587;

How to build and use Google TensorFlow C++ api

If you don't want to build Tensorflow yourself and your operating system is Debian or Ubuntu, you can download prebuilt packages with the Tensorflow C/C++ libraries. This distribution can be used for C/C++ inference with CPU, GPU support is not included:

https://github.com/kecsap/tensorflow_cpp_packaging/releases

There are instructions written how to freeze a checkpoint in Tensorflow (TFLearn) and load this model for inference with the C/C++ API:

https://github.com/kecsap/tensorflow_cpp_packaging/blob/master/README.md

Beware: I am the developer of this Github project.

What is an application binary interface (ABI)?

The term ABI is used to refer to two distinct but related concepts.

When talking about compilers it refers to the rules used to translate from source-level constructs to binary constructs. How big are the data types? how does the stack work? how do I pass parameters to functions? which registers should be saved by the caller vs the callee?

When talking about libraries it refers to the binary interface presented by a compiled library. This interface is the result of a number of factors including the source code of the library, the rules used by the compiler and in some cases definitions picked up from other libraries.

Changes to a library can break the ABI without breaking the API. Consider for example a library with an interface like.

void initfoo(FOO * foo)
int usefoo(FOO * foo, int bar)
void cleanupfoo(FOO * foo)

and the application programmer writes code like

int dostuffwithfoo(int bar) {
  FOO foo;
  initfoo(&foo);
  int result = usefoo(&foo,bar)
  cleanupfoo(&foo);
  return result;
}

The application programmer doesn't care about the size or layout of FOO, but the application binary ends up with a hardcoded size of foo. If the library programmer adds an extra field to foo and someone uses the new library binary with the old application binary then the library may make out of bounds memory accesses.

OTOH if the library author had designed their API like.

FOO * newfoo(void)
int usefoo(FOO * foo, int bar)
void deletefoo((FOO * foo, int bar))

and the application programmer writes code like

int dostuffwithfoo(int bar) {
  FOO * foo;
  foo = newfoo();
  int result = usefoo(foo,bar)
  deletefoo(foo);
  return result;
}

Then the application binary does not need to know anything about the structure of FOO, that can all be hidden inside the library. The price you pay for that though is that heap operations are involved.

HTML Form: Select-Option vs Datalist-Option

Think of it as the difference between a requirement and a suggestion. For the select element, the user is required to select one of the options you've given. For the datalist element, it is suggested that the user select one of the options you've given, but he can actually enter anything he wants in the input.

Edit 1: So which one you use depends upon your requirements. If the user must enter one of your choices, use the select element. If the use can enter whatever, use the datalist element.

Edit 2: Found this tidbit in the HTML Living Standard: "Each option element that is a descendant of the datalist element...represents a suggestion."

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

How to dynamically change the color of the selected menu item of a web page?

At last I managed to achieve what I intended with all your help and the post Change a link style onclick. Here is the code for that. I used JavaScript for doing this.

<html>
    <head>
        <style type="text/css">
            .item {
                width:900px;
                padding:0;
                margin:0;
                list-style-type:none;
            }

            a {
                display:block;
                width:60;
                line-height:25px; /*24px*/
                border-bottom:1px  none #808080;
                font-family:'arial narrow',sans-serif;
                color:#00F;
                text-align:center;
                text-decoration:none;
                background:#CCC;
                border-radius: 5px;
                -webkit-border-radius: 5px;
                -moz-border-radius: 5px;
                margin-bottom:0em;
                padding: 0px;
            }

            a.item {
                float:left;        /* For horizontal left to right display. */
                width:145px;       /* For maintaining equal  */
                margin-right: 5px; /* space between two boxes. */
            }

            a.selected{
                background:orange;
                color:white;
            }
        </style>
    </head>
    <body>
        <a class="item" href="#" >item 1</a>
        <a class="item" href="#" >item 2</a>
        <a class="item" href="#" >item 3</a>
        <a class="item" href="#" >item 4</a>
        <a class="item" href="#" >item 5</a>
        <a class="item" href="#" >item 6</a>

        <script>
            var anchorArr=document.getElementsByTagName("a");
            var prevA="";
            for(var i=0;i<anchorArr.length;i++)
            {
                anchorArr[i].onclick = function(){
                    if(prevA!="" && prevA!=this)
                    {
                        prevA.className="item";
                    }
                    this.className="item selected";
                    prevA=this;
                }
            }
        </script>
    </body>
</html>

How to center a component in Material-UI and make it responsive?

Since you are going to use this in a login page. Here is a code I used in a Login page using Material-UI

<Grid
  container
  spacing={0}
  direction="column"
  alignItems="center"
  justify="center"
  style={{ minHeight: '100vh' }}
>

  <Grid item xs={3}>
    <LoginForm />
  </Grid>   

</Grid> 

this will make this login form at the center of the screen.

But still IE doesn't support the Material-UI Grid and you will see some misplaced content in IE.

Hope this will help you.

How to make flutter app responsive according to different screen size?

check out this page from flutter wiki :

Creating Responsive Apps

Use the LayoutBuilder class: From its builder property, you get a BoxConstraints. Examine the constraint's properties to decide what to display. For example, if your maxWidth is greater than your width breakpoint, return a Scaffold object with a row that has a list on the left. If it's narrower, return a Scaffold object with a drawer containing that list. You can also adjust your display based on the device's height, the aspect ratio, or some other property. When the constraints change (e.g. the user rotates the phone, or puts your app into a tile UI in Nougat), the build function will rerun.

How to insert a data table into SQL Server database table?

I found that it was better to add to the table row by row if your table has a primary key. Inserting the entire table at once creates a conflict on the auto increment.

Here's my stored Proc

CREATE PROCEDURE dbo.usp_InsertRowsIntoTable
@Year       int,
@TeamName   nvarchar(50),
AS
INSERT INTO [dbo.TeamOverview]
(Year,TeamName)
VALUES (@Year, @TeamName);
RETURN

I put this code in a loop for every row that I need to add to my table:

insertRowbyRowIntoTable(Convert.ToInt16(ddlChooseYear.SelectedValue), name);

And here is my Data Access Layer code:

        public void insertRowbyRowIntoTable(int ddlValue, string name)
    { 
        SqlConnection cnTemp = null;
        string spName = null;
        SqlCommand sqlCmdInsert = null;

        try
        {
            cnTemp = helper.GetConnection();
            using (SqlConnection connection = cnTemp)
            {
                if (cnTemp.State != ConnectionState.Open)
                    cnTemp.Open();
                using (sqlCmdInsert = new SqlCommand(spName, cnTemp))
                {
                    spName = "dbo.usp_InsertRowsIntoOverview";
                    sqlCmdInsert = new SqlCommand(spName, cnTemp);
                    sqlCmdInsert.CommandType = CommandType.StoredProcedure;

                    sqlCmdInsert.Parameters.AddWithValue("@Year", ddlValue);
                    sqlCmdInsert.Parameters.AddWithValue("@TeamName", name);

                    sqlCmdInsert.ExecuteNonQuery();

                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (sqlCmdInsert != null)
                sqlCmdInsert.Dispose();

            if (cnTemp.State == ConnectionState.Open)
                cnTemp.Close();
        }

    }

Sending and Parsing JSON Objects in Android

You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK

Shortcut key for commenting out lines of Python code in Spyder

Yes, there is a shortcut for commenting out lines in Python 3.6 (Spyder).

For Single Line Comment, you can use Ctrl+1. It will look like this #This is a sample piece of code

For multi-line comments, you can use Ctrl+4. It will look like this

#============= \#your piece of code \#some more code \#=============

Note : \ represents that the code is carried to another line.

How to make/get a multi size .ico file?

Fresh answer 2018:

Step 1 Launch Microsoft Paint. Not Paint.Net but plain Paint

Step 2 Open the image you want to convert to icon format by clicking the “Paint” toolbar tab and selecting “Open.”

Step 3 Click the “Paint” tab, highlight the “Save As” option and select the “BMP picture” option. As 256-colored. There is a dropdown list.

Step 4 You have to open it in Paint.net now. Enter a file name for the icon and type “.ico” (without quotations) as the file extension. Select your preferred output folder for the icon and click “Save.”(still in bmp type) , exposing auto definition in saving parameters window.

This is a solution for those WHO DOESN'T WANT THE THIRD PARTY APPS TO GAIN PERMISSIONS ON THEIR COMP.
I use this simple way to create custom icons for folders on my desktop or documents.

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

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

Registry keys to enable use of strong crypto:

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

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

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.

It would be nice if you could do the following:

SELECT DATETIME(col, 'PDT')

...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.

Doesn't deal with daylight saving rules, though...

Read file data without saving it in Flask

In case we want to dump the in memory file to disk. This code can be used

  if isinstanceof(obj,SpooledTemporaryFile):
    obj.rollover()

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

When you see dtype('O') inside dataframe this means Pandas string.

What is dtype?

Something that belongs to pandas or numpy, or both, or something else? If we examine pandas code:

df = pd.DataFrame({'float': [1.0],
                    'int': [1],
                    'datetime': [pd.Timestamp('20180310')],
                    'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype

It will output like this:

   float  int   datetime string    
0    1.0    1 2018-03-10    foo
---
float64 int64 datetime64[ns] object
---
dtype('O')

You can interpret the last as Pandas dtype('O') or Pandas object which is Python type string, and this corresponds to Numpy string_, or unicode_ types.

Pandas dtype    Python type     NumPy type          Usage
object          str             string_, unicode_   Text

Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype for that.

Data type object is an instance of numpy.dtype class that understand the data type more precise including:

  • Type of the data (integer, float, Python object, etc.)
  • Size of the data (how many bytes is in e.g. the integer)
  • Byte order of the data (little-endian or big-endian)
  • If the data type is structured, an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float)
  • What are the names of the "fields" of the structure
  • What is the data-type of each field
  • Which part of the memory block each field takes
  • If the data type is a sub-array, what is its shape and data type

In the context of this question dtype belongs to both pands and numpy and in particular dtype('O') means we expect the string.


Here is some code for testing with explanation: If we have the dataset as dictionary

import pandas as pd
import numpy as np
from pandas import Timestamp

data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe

print(df)
print(df.dtypes)

The last lines will examine the dataframe and note the output:

   id       date                  role  num   fnum
0   1 2018-12-12               Support  123   3.14
1   2 2018-12-12             Marketing  234   2.14
2   3 2018-12-12  Business Development  345  -0.14
3   4 2018-12-12                 Sales  456  41.30
4   5 2018-12-12           Engineering  567   3.14
id               int64
date    datetime64[ns]
role            object
num              int64
fnum           float64
dtype: object

All kind of different dtypes

df.iloc[1,:] = np.nan
df.iloc[2,:] = None

But if we try to set np.nan or None this will not affect the original column dtype. The output will be like this:

print(df)
print(df.dtypes)

    id       date         role    num   fnum
0  1.0 2018-12-12      Support  123.0   3.14
1  NaN        NaT          NaN    NaN    NaN
2  NaN        NaT         None    NaN    NaN
3  4.0 2018-12-12        Sales  456.0  41.30
4  5.0 2018-12-12  Engineering  567.0   3.14
id             float64
date    datetime64[ns]
role            object
num            float64
fnum           float64
dtype: object

So np.nan or None will not change the columns dtype, unless we set the all column rows to np.nan or None. In that case column will become float64 or object respectively.

You may try also setting single rows:

df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object

And to note here, if we set string inside a non string column it will become string or object dtype.

IIS Express Windows Authentication

Visual Studio 2010 SP1 and 2012 added support for IIS Express eliminating the need to edit angle brackets.

  1. If you haven't already, right-click a web-flavored project and select "Use IIS Express...".
  2. Once complete, select the web project and press F4 to focus the Properties panel.
  3. Set the "Windows Authentication" property to Enabled, and the "Anonymous Authentication" property to Disabled.

enter image description here

I believe this solution is superior to the vikomall's options.

  • Option #1 is a global change for all IIS Express sites.
  • Option #2 leaves development cruft in the web.config.
    • Further, it will probably lead to an error when deployed to IIS 7.5 unless you follow the "unlock" procedure on your IIS server's applicationHost.config.

The UI-based solution above uses site-specific location elements in IIS Express's applicationHost.config leaving the app untouched.

More information here: http://msdn.microsoft.com/en-us/magazine/hh288080.aspx

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

On read csv, I added an encoding method:

import pandas as pd
dataset = pd.read_csv('sample_data.csv', header= 0,
                        encoding= 'unicode_escape')

How to write logs in text file when using java.util.logging.Logger

Try this sample. It works for me.

public static void main(String[] args) {  

    Logger logger = Logger.getLogger("MyLog");  
    FileHandler fh;  

    try {  

        // This block configure the logger with handler and formatter  
        fh = new FileHandler("C:/temp/test/MyLogFile.log");  
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);  

        // the following statement is used to log any messages  
        logger.info("My first log");  

    } catch (SecurityException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  

    logger.info("Hi How r u?");  

}

Produces the output at MyLogFile.log

Apr 2, 2013 9:57:08 AM testing.MyLogger main  
INFO: My first log  
Apr 2, 2013 9:57:08 AM testing.MyLogger main  
INFO: Hi How r u?

Edit:

To remove the console handler, use

logger.setUseParentHandlers(false);

since the ConsoleHandler is registered with the parent logger from which all the loggers derive.

'innerText' works in IE, but not in Firefox

This has been my experience with innerText, textContent, innerHTML, and value:

// elem.innerText = changeVal;  // works on ie but not on ff or ch
// elem.setAttribute("innerText", changeVal); // works on ie but not ff or ch
// elem.textContent = changeVal;  // works on ie but not ff or ch
// elem.setAttribute("textContent", changeVal);  // does not work on ie ff or ch
// elem.innerHTML = changeVal;  // ie causes error - doesn't work in ff or ch
// elem.setAttribute("innerHTML", changeVal); //ie causes error doesn't work in ff or ch
   elem.value = changeVal; // works in ie and ff -- see note 2 on ch
// elem.setAttribute("value", changeVal); // ie works; see note 1 on ff and note 2 on ch

ie = internet explorer, ff = firefox, ch = google chrome. note 1: ff works until after value is deleted with backspace - see note by Ray Vega above. note 2: works somewhat in chrome - after update it is unchanged then you click away and click back into the field and the value appears. The best of the lot is elem.value = changeVal; which I did not comment out above.

How to stretch div height to fill parent div - CSS

B2 container position relative

Top position B2 + of remaining height

Height of B2 + height B1 or remaining height

FB OpenGraph og:image not pulling images (possibly https?)

I had the same error and nothing of previous have helped, so I tried to follow original documentation of Open Graph Protocol and I added prefix attribute to my html tag and everything became awesome.

<html prefix="og: http://ogp.me/ns#">

Django auto_now and auto_now_add

But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs #7634 and #12785), auto_now and auto_now_add are not going anywhere, and even if you go to the original discussion, you'll find strong arguments against the RY (as in DRY) in custom save methods.

A better solution has been offered (custom field types), but didn't gain enough momentum to make it into django. You can write your own in three lines (it's Jacob Kaplan-Moss' suggestion).

from django.db import models
from django.utils import timezone


class AutoDateTimeField(models.DateTimeField):
    def pre_save(self, model_instance, add):
        return timezone.now()

#usage
created_at = models.DateField(default=timezone.now)
updated_at = models.AutoDateTimeField(default=timezone.now)

Javascript format date / time

You can do that:

function formatAMPM(date) { // This is to display 12 hour format like you asked
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);

Fiddle

What characters do I need to escape in XML documents?

In addition to the commonly known five characters [<, >, &, ", and '], I would also escape the vertical tab character (0x0B). It is valid UTF-8, but not valid XML 1.0, and even many libraries (including the highly portable (ANSI C) library libxml2) miss it and silently output invalid XML.