Programs & Examples On #Spatstat

spatstat is an R package for analysing spatial data, mainly Spatial Point Patterns.

Setting Oracle 11g Session Timeout

I came to this question looking for a way to enable oracle session pool expiration based on total session lifetime instead of idle time. Another goal is to avoid force closes unexpected to application.

It seems it's possible by setting pool validation query to

select 1 from V$SESSION 
where AUDSID = userenv('SESSIONID') and sysdate-LOGON_TIME < 30/24/60

This would close sessions aging over 30 minutes in predictable manner that doesn't affect application.

What's "P=NP?", and why is it such a famous question?

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

Excel Define a range based on a cell value

You can also use OFFSET:

OFFSET($A$10,-$B$1+1,0,$B$1)

It moves the range $A$10 up by $B$1-1 (becomes $A$6 ($A$5)) and then resizes the range to $B$1 rows (becomes $A$6:$A$10 ($A$5:$A$10))

How can I make the cursor turn to the wait cursor?

Okey,Other people's view are very clear, but I would like to do some added, as follow:

Cursor tempCursor = Cursor.Current;

Cursor.Current = Cursors.WaitCursor;

//do Time-consuming Operations         

Cursor.Current = tempCursor;

How do I uninstall nodejs installed from pkg (Mac OS X)?

A little convenience script expanding on previous answers.

#!/bin/bash

# Uninstall node.js
# 
# Options:
#
# -d Actually delete files, otherwise the script just _prints_ a command to delete.
# -p Installation prefix. Default /usr/local
# -f BOM file. Default /var/db/receipts/org.nodejs.pkg.bom

CMD="echo sudo rm -fr"
BOM_FILE="/var/db/receipts/org.nodejs.pkg.bom"
PREFIX="/usr/local"

while getopts "dp:f:" arg; do
    case $arg in
        d)
            CMD="sudo rm -fr"
            ;;
        p)
            PREFIX=$arg
            ;;
        f)
            BOM_FILE=$arg
            ;;
    esac
done

lsbom -f -l -s -pf ${BOM_FILE} \
    | while read i; do
          $CMD ${PREFIX}/${i}
      done

$CMD ${PREFIX}/lib/node \
     ${PREFIX}/lib/node_modules \
     ${BOM_FILE}

Save it to file and run with:

# bash filename.sh

angular2 submit form by pressing enter without submit button

Most answers here suggest using something like:

<form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="yourMethod()">

</form>

This approach does not result in the form object being marked as submitted. You might not care for this, but if you're using something like @ngspot/ngx-errors (shameless self-promotion) for displaying validation errors, you gonna want to fix that. Here's how:

<form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="submitBtn.click()">
  <button #submitBtn>Submit</button>
</form>

The best way to remove duplicate values from NSMutableArray in Objective-C?

I know this is an old question, but there is a more elegant way to remove duplicates in a NSArray if you don't care about the order.

If we use Object Operators from Key Value Coding we can do this:

uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];

As AnthoPak also noted it is possible to remove duplicates based on a property. An example would be: @distinctUnionOfObjects.name

How to show full height background image?

CSS can do that with background-size: cover;

But to be more detailed and support more browsers...

Use aspect ratio like this:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

Replace a value in a data frame based on a conditional (`if`) statement

If you are working with character variables (note that stringsAsFactors is false here) you can use replace:

junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12], stringsAsFactors = FALSE)
colnames(junk) <- c("nm", "val")

junk$nm <- replace(junk$nm, junk$nm == "B", "b")
junk
#    nm val
# 1   A   a
# 2   b   b
# 3   C   c
# 4   D   d
# ...

Fixed header, footer with scrollable content

If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/

HTML

<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">Body</div>
    <footer><h3>Footer</h3></footer>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
}

header {
    flex-shrink: 0;
}
.body{
    flex-grow: 1;
    overflow: auto;
    min-height: 2em;
}
footer{
    flex-shrink: 0;
}

Update:
See "Can I use" for browser support of flexible boxes.

Difference between spring @Controller and @RestController annotation

As you can see in Spring documentation (Spring RestController Documentation) Rest Controller annotation is the same as Controller annotation, but assuming that @ResponseBody is active by default, so all the Java objects are serialized to JSON representation in the response body.

How to NodeJS require inside TypeScript file?

Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:

declare function require(name:string);
var sampleModule = require('modulename');

On my system, this compiles just fine.

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

Execute PHP function with onclick

In javascript, make an ajax function,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

<a href="" onclick="myAjax()" class="deletebtn">Delete</a>

And in your ajax.php,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}

Cassandra port usage - how are the ports used?

In addition to the above answers, as part of configuring your firewall, if you are using SSH then use port 22.

How to split a delimited string in Ruby and convert it to an array?

the simplest way to convert a string that has a delimiter like a comma is just to use the split method

"1,2,3,4".split(',') # "1", "2", "3", "4"]

you can find more info on how to use the split method in the ruby docs

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

Using RegEX To Prefix And Append In Notepad++

Why don't you use the Notepad++ multiline editing capabilities?

Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.

You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.

How can I implement the Iterable interface?

Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.

So I would at least change it to:

public class ProfileCollection implements Iterable<Profile> { 
    private ArrayList<Profile> m_Profiles;

    public Iterator<Profile> iterator() {        
        Iterator<Profile> iprof = m_Profiles.iterator();
        return iprof; 
    }

    ...

    public Profile GetActiveProfile() {
        return (Profile)m_Profiles.get(m_ActiveProfile);
    }
}

and this should work:

for (Profile profile : m_PC) {
    // do stuff
}

Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:

for (Object profile : m_PC) {
    // do stuff
}

This is a pretty obscure corner case of Java generics.

If not, please provide some more info about what's going on.

Trigger standard HTML5 validation (form) without using submit button?

I know it is an old topic, but when there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

How to bind Events on Ajax loaded Content?

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:

How to Create simple drag and Drop in angularjs

small scripts for drag and drop by angular

(function(angular) {
  'use strict';
angular.module('drag', []).
  directive('draggable', function($document) {
    return function(scope, element, attr) {
      var startX = 0, startY = 0, x = 0, y = 0;
      element.css({
       position: 'relative',
       border: '1px solid red',
       backgroundColor: 'lightgrey',
       cursor: 'pointer',
       display: 'block',
       width: '65px'
      });
      element.on('mousedown', function(event) {
        // Prevent default dragging of selected content
        event.preventDefault();
        startX = event.screenX - x;
        startY = event.screenY - y;
        $document.on('mousemove', mousemove);
        $document.on('mouseup', mouseup);
      });

      function mousemove(event) {
        y = event.screenY - startY;
        x = event.screenX - startX;
        element.css({
          top: y + 'px',
          left:  x + 'px'
        });
      }

      function mouseup() {
        $document.off('mousemove', mousemove);
        $document.off('mouseup', mouseup);
      }
    };
  });
})(window.angular);

source link

Unused arguments in R

One approach (which I can't imagine is good programming practice) is to add the ... which is traditionally used to pass arguments specified in one function to another.

> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8

You can read more about ... is intended to be used here

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

One simple solution for me that worked was to : - Restart the IDE, since the stop Button was no longer visible.

libclntsh.so.11.1: cannot open shared object file.

I had to install the dependency

oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64

TypeError: $(...).modal is not a function with bootstrap Modal

i just want to emphasize what mwebber said in the comment:

also check if jQuery is not included twice

:)

it was the issue for me

How to clear out session on log out

<script runat="server">  
    protected void Page_Load(object sender, System.EventArgs e) {  
        Session["FavoriteSoftware"] = "Adobe ColdFusion";  
        Label1.Text = "Session read...<br />";  
        Label1.Text += "Favorite Software : " + Session["FavoriteSoftware"];  
        Label1.Text += "<br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br> Now clear the current session data.";  
        Session.Clear();  
        Label1.Text += "<br /><br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br />Favorite Software[after clear]: " + Session["FavoriteSoftware"];  
    }  
</script>  



<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>asp.net session Clear example: how to clear the current session data (remove all the session items)</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:Teal">asp.net session example: Session Clear</h2>  
        <asp:Label   
            ID="Label1"   
            runat="server"   
            Font-Size="Large"  
            ForeColor="DarkMagenta"  
            >  
        </asp:Label>  
    </div>  
    </form>  
</body>  
</html>  

How to convert an array to object in PHP?

The one I use (it is a class member):

const MAX_LEVEL = 5; // change it as needed

public function arrayToObject($a, $level=0)
{

    if(!is_array($a)) {
        throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
    }

    if($level > self::MAX_LEVEL) {
        throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
    }

    $o = new stdClass();
    foreach($a as $key => $value) {
        if(is_array($value)) { // convert value recursively
            $value = $this->arrayToObject($value, $level+1);
        }
        $o->{$key} = $value;
    }
    return $o;
}

How can I exclude multiple folders using Get-ChildItem -exclude?

VertigoRay, in his answer, explained that -Exclude works only at the leaf level of a path (for a file the filename with path stripped out; for a sub-directory the directory name with path stripped out). So it looks like -Exclude cannot be used to specify a directory (eg "bin") and exclude all the files and sub-directories within that directory.

Here's a function to exclude files and sub-directories of one or more directories (I know this is not directly answering the question but I thought it might be useful in getting around the limitations of -Exclude):

$rootFolderPath = 'C:\Temp\Test'
$excludeDirectories = ("bin", "obj");

function Exclude-Directories
{
    process
    {
        $allowThrough = $true
        foreach ($directoryToExclude in $excludeDirectories)
        {
            $directoryText = "*\" + $directoryToExclude
            $childText = "*\" + $directoryToExclude + "\*"
            if (($_.FullName -Like $directoryText -And $_.PsIsContainer) `
                -Or $_.FullName -Like $childText)
            {
                $allowThrough = $false
                break
            }
        }
        if ($allowThrough)
        {
            return $_
        }
    }
}

Clear-Host

Get-ChildItem $rootFolderPath -Recurse `
    | Exclude-Directories

For a directory tree:

C:\Temp\Test\
|
+?SomeFolder\
|  |
|  +?bin (file without extension)
|
+?MyApplication\
  |
  +?BinFile.txt
  +?FileA.txt
  +?FileB.txt
  |
  +?bin\
    |
    +?Debug\
      |
      +?SomeFile.txt

The result is:

C:\Temp\Test\
|
+?SomeFolder\
|  |
|  +?bin (file without extension)
|
+?MyApplication\
  |
  +?BinFile.txt
  +?FileA.txt
  +?FileB.txt

It excludes the bin\ sub-folder and all its contents but does not exclude files Bin.txt or bin (file named "bin" without an extension).

HttpContext.Current.User.Identity.Name is Empty

Apart from all obvious reasons mentioned earlier, there might be another one: you didn't put an Authorize attribute on top of your controller, like that:

[Authorize(Roles = "myRole")]
[EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*", SupportsCredentials = true)]
public class MyController : ApiController

At least that's what worked for me.

Get all child views inside LinearLayout at once

Use getChildCount() and getChildAt(int index).

Example:

LinearLayout ll = …
final int childCount = ll.getChildCount();
for (int i = 0; i < childCount; i++) {
      View v = ll.getChildAt(i);
      // Do something with v.
      // …
}

There is already an open DataReader associated with this Command which must be closed first

This can happen if you execute a query while iterating over the results from another query. It is not clear from your example where this happens because the example is not complete.

One thing that can cause this is lazy loading triggered when iterating over the results of some query.

This can be easily solved by allowing MARS in your connection string. Add MultipleActiveResultSets=true to the provider part of your connection string (where Data Source, Initial Catalog, etc. are specified).

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

textarea's rows, and cols attribute in CSS

I don't think you can. I always go with height and width.

textarea{
width:400px;
height:100px;
}

the nice thing about doing it the CSS way is that you can completely style it up. Now you can add things like:

textarea{
width:400px;
height:100px;
border:1px solid #000000;
background-color:#CCCCCC;
}

How to send file contents as body entity using cURL

In my case, @ caused some sort of encoding problem, I still prefer my old way:

curl -d "$(cat /path/to/file)" https://example.com

What is the function of the push / pop instructions used on registers in x86 assembly?

Pushing and popping registers are behind the scenes equivalent to this:

push reg   <= same as =>      sub  $8,%rsp        # subtract 8 from rsp
                              mov  reg,(%rsp)     # store, using rsp as the address

pop  reg    <= same as=>      mov  (%rsp),reg     # load, using rsp as the address
                              add  $8,%rsp        # add 8 to the rsp

Note this is x86-64 At&t syntax.

Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Object not found! The requested URL was not found on this server. localhost

I also had same error but with codeigniter application. I changed

  • my base URL in config.php to my localhost path

  • in htaccess I changed RewriteBase /"my folder name in htdocs"

    and I able to login to my application.

Hope it might help.

Html table tr inside td

Put another table inside the td element like this.

<table>
    <tr>
        ...
    </tr>
    <tr>
        <td>ABC</td>
        <td>ABC</td>
        <td>
            <table>
                <tr>
                    <td>name1</td>
                    <td>price1</td>
                </tr>
...
            </table>
        </td>
        <td>ABC</td>
    </tr>
...
</table>

is of a type that is invalid for use as a key column in an index

A solution would be to declare your key as nvarchar(20).

Python and SQLite: insert into table

Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:

def sqlite_insert(conn, table, row):
    cols = ', '.join('"{}"'.format(col) for col in row.keys())
    vals = ', '.join(':{}'.format(col) for col in row.keys())
    sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
    conn.cursor().execute(sql, row)
    conn.commit()

Example of use:

sqlite_insert(conn, 'stocks', {
        'created_at': '2016-04-17',
        'type': 'BUY',
        'amount': 500,
        'price': 45.00})

Note, that table name and column names should be validated beforehand.

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

You dont need both jTDS and JDBC in your classpath. Any one is required. Here you need only sqljdbc.jar.

Also, I would suggest to place sqljdbc.jar at physical location to /WEB-INF/lib directory of your project rather than adding it in the Classpath via IDE. Then Tomcat takes care the rest. And also try restarting Tomcat.

You can download Jar from : www.java2s.com/Code/JarDownload/sqlserverjdbc/sqlserverjdbc.jar.zip

EDIT:

As you are supplying Username and Password when connecting,

You need only jdbc:sqlserver://localhost:1433;databaseName=test, Skip integratedSecurity attribute.

How do you do dynamic / dependent drop downs in Google Sheets?

Edit: The answer below may be satisfactory, but it has some drawbacks:

  1. There is a noticeable pause for the running of the script. I'm on a 160 ms latency, and it's enough to be annoying.

  2. It works by building a new range each time you edit a given row. This gives an 'invalid contents' to previous entries some of the time

I hope others can clean this up somewhat.

Here's another way to do it, that saves you a ton of range naming:

Three sheets in the worksheet: call them Main, List, and DRange (for dynamic range.) On the Main sheet, column 1 contains a timestamp. This time stamp is modified onEdit.

On List your categories and subcategories are arranged as a simple list. I'm using this for plant inventory at my tree farm, so my list looks like this:

Group   | Genus | Bot_Name
Conifer | Abies | Abies balsamea
Conifer | Abies | Abies concolor
Conifer | Abies | Abies lasiocarpa var bifolia
Conifer | Pinus | Pinus ponderosa
Conifer | Pinus | Pinus sylvestris
Conifer | Pinus | Pinus banksiana
Conifer | Pinus | Pinus cembra
Conifer | Picea | Picea pungens
Conifer | Picea | Picea glauca
Deciduous | Acer | Acer ginnala
Deciduous | Acer | Acer negundo
Deciduous | Salix | Salix discolor
Deciduous | Salix | Salix fragilis
...

Where | indicates separation into columns.
For convenience I also used the headers as names for named ranges.

DRrange A1 has the formula

=Max(Main!A2:A1000)

This returns the most recent timestamp.

A2 to A4 have variations on:

=vlookup($A$1,Inventory!$A$1:$E$1000,2,False) 

with the 2 being incremented for each cell to the right.

On running A2 to A4 will have the currently selected Group, Genus and Species.

Below each of these, is a filter command something like this:

=unique(filter(Bot_Name,REGEXMATCH(Bot_Name,C1)))

These filters will populate a block below with matching entries to the contents of the top cell.

The filters can be modified to suit your needs, and to the format of your list.

Back to Main: Data validation in Main is done using ranges from DRange.

The script I use:

function onEdit(event) {

  //SETTINGS
  var dynamicSheet='DRange'; //sheet where the dynamic range lives
  var tsheet = 'Main'; //the sheet you are monitoring for edits
  var lcol = 2; //left-most column number you are monitoring; A=1, B=2 etc
  var rcol = 5; //right-most column number you are monitoring
  var tcol = 1; //column number in which you wish to populate the timestamp
  //

  var s = event.source.getActiveSheet();
  var sname = s.getName();
  if (sname == tsheet) {
    var r = event.source.getActiveRange();
    var scol = r.getColumn();  //scol is the column number of the edited cell
    if (scol >= lcol && scol <= rcol) {
      s.getRange(r.getRow(), tcol).setValue(new Date());
      for(var looper=scol+1; looper<=rcol; looper++) {
         s.getRange(r.getRow(),looper).setValue(""); //After edit clear the entries to the right
      }
    }
  }
}

Original Youtube presentation that gave me most of the onEdit timestamp component: https://www.youtube.com/watch?v=RDK8rjdE85Y

How to get current class name including package name in Java?

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

ASP.NET Core Get Json Array using IConfiguration

DotNet Core 3.1:

Json config:

"TestUsers": 
{
    "User": [
    {
      "UserName": "TestUser",
      "Email": "[email protected]",
      "Password": "P@ssw0rd!"
    },
    {
      "UserName": "TestUser2",
      "Email": "[email protected]",
      "Password": "P@ssw0rd!"
    }]
}

Then create a User.cs class with auto properties that corresponds to User objects in the Json config above. Then you can reference Microsoft.Extensions.Configuration.Abstractions and do:

List<User> myTestUsers = Config.GetSection("TestUsers").GetSection("User").Get<List<User>>();

List of all unique characters in a string?

if the result does not need to be order-preserving, then you can simply use a set

>>> ''.join(set( "aaabcabccd"))
'acbd'
>>>

What is Model in ModelAndView from Spring MVC?

The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.

Example 1

If you have...

return new ModelAndView("welcomePage","WelcomeMessage","Welcome!");

... then in your jsp, to display the message, you will do:-

Hello Stranger! ${WelcomeMessage} // displays Hello Stranger! Welcome!

Example 2

If you have...

MyBean bean = new MyBean();
bean.setName("Mike!");
bean.setMessage("Meow!");

return new ModelAndView("welcomePage","model",bean);

... then in your jsp, you can do:-

Hello ${model.name}! {model.message} // displays Hello Mike! Meow!

Getting value GET OR POST variable using JavaScript?

// Captura datos usando metodo GET en la url colocar index.html?hola=chao
const $_GET = {};
const args = location.search.substr(1).split(/&/);
for (let i=0; i<args.length; ++i) {
    const tmp = args[i].split(/=/);
    if (tmp[0] != "") {
        $_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
        console.log(`>>${$_GET['hola']}`);
    }//::END if
}//::END for

How do I add a border to an image in HTML?

Here is some HTML and CSS code that would solve your issue:

CSS

.ImageBorder
{
    border-width: 1px;
    border-color: Black;
}

HTML

<img src="MyImage.gif" class="ImageBorder" />

How to find whether a ResultSet is empty or not in Java?

if (rs == null || !rs.first()) {
    //empty
} else {
    //not empty
}

Note that after this method call, if the resultset is not empty, it is at the beginning.

How to Check whether Session is Expired or not in asp.net

Check if it is null or not e.g

if(Session["mykey"] != null)
{
  // Session is not expired
}
else
{
  //Session is expired
}

Why can't overriding methods throw exceptions broader than the overridden method?

In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).

Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.

HTML5 Form Input Pattern Currency Format

I'm wrote this price pattern without zero price.

(0\.((0[1-9]{1})|([1-9]{1}([0-9]{1})?)))|(([1-9]+[0-9]*)(\.([0-9]{1,2}))?)

Valid For:

  • 1.00
  • 1
  • 1.5
  • 0.10
  • 0.1
  • 0.01
  • 2500.00

Invalid For:

  • 0
  • 0.00
  • 0.0
  • 2500.
  • 2500.0000

Check my code online: http://regexr.com/3binj

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I had the same issue with firefox 38.

After using following version dependencies, I could resolve the issue.

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.0</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>2.53.0</version>
    </dependency> 

how to use JSON.stringify and json_decode() properly

I don't how this works, but it worked.

$post_data = json_decode(json_encode($_POST['request_key']));

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

Hash # symbol creating this error, if you can remove the # from the start of the column name, it could fix the problem.

Basically, when the column name starts with # in between rows, read.table() will recognise as a starting point for that row.

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

How do I make a div full screen?

.widget-HomePageSlider .slider-loader-hide {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    z-index: 10000;
    background: white;
}

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

In my case, the "Default Web Site" in IIS didn't have a binding for localhost on port 80. You should have a binding for whatever your value in the .csproj file is.

How to Copy Text to Clip Board in Android?

to search clip board list first get the clipboard object like this :

private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

then check if there is any data in clip board by this function :

fun isClipboardContainsData() : Boolean{
        return when{
            !clipboard.hasPrimaryClip() -> false
            else -> true
        }
    }

then use this function to go through the clipboard object like below:

fun searchClipboard() : ClipData.Item? {
        return if (isClipboardContainsData()){

            val items = clipboard.primaryClip
            val clipboardSize = items?.itemCount ?: 0
            for (i in 0..clipboardSize) {
                val item = items?.getItemAt(i)
                return if (item != null){
                       return item
                }else
                    null
            }
            return null
        }else
            null

    }

here you can see that the searchClipboard Item will return an item of type ClipData.Item, the clipboard contains a list of ClipData.Item and if you go through implementation of clipboard this is what you will find about ClipData.Item:

public static class Item {
    final CharSequence mText;
    final String mHtmlText;
    final Intent mIntent;
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    Uri mUri;
}

so what you can hold in a clipboard item could be of type:

  1. CharSequence
  2. String
  3. Intent(this supports copying application shortcuts)
  4. Uri (for copying complex data from a content provider)

How to set default font family for entire Android app

To change your app font follow the following steps:

  1. Inside res directory create a new directory and name it font.
  2. Insert your font .ttf/.otf inside the font folder, Make sure the font name is lower case letters and underscore only.
  3. Inside res -> values -> styles.xml inside <resources> -> <style> add your font <item name="android:fontFamily">@font/font_name</item>.

enter image description here

Now all your app text should be in the font that you add.

How can I list the contents of a directory in Python?

Below code will list directories and the files within the dir. The other one is os.walk

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)

Convert multidimensional array into single array

I've written a complement to the accepted answer. In case someone, like myself need a prefixed version of the keys, this can be helpful.

Array
(
    [root] => Array
        (
            [url] => http://localhost/misc/markia
        )

)
Array
(
    [root.url] => http://localhost/misc/markia
)
<?php
function flattenOptions($array, $old = '') {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, flattenOptions($value, $key));
    }
    else {
      $result[$old . '.' . $key] = $value;
    }
  }
  return $result;
}

Can an AWS Lambda function call another

There are a lot of answers, but none is stressing that calling another lambda function is not recommended solution for synchronous calls and the one that you should be using is really Step Functions

Reasons why it is not recommended solution:

  • you are paying for both functions
  • your code is responsible for retrials

You can also use it for quite complex logic, such as parallel steps and catch failures. Every execution is also being logged out which makes debugging much simpler.

Detect changed input text box

onkeyup, onpaste, onchange, oninput seems to be failing when the browser performs autofill on the textboxes. To handle such a case include "autocomplete='off'" in your textfield to prevent browser from autofilling the textbox,

Eg,

<input id="inputDatabaseName" autocomplete='off' onchange="check();"
 onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />

<script>
     function check(){
          alert("Input box changed");
          // Things to do when the textbox changes
     }
</script>

Read large files in Java

This is a very good article: http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/

In summary, for great performance, you should:

  1. Avoid accessing the disk.
  2. Avoid accessing the underlying operating system.
  3. Avoid method calls.
  4. Avoid processing bytes and characters individually.

For example, to reduce the access to disk, you can use a large buffer. The article describes various approaches.

How to post data to specific URL using WebClient in C#

There is a built in method called UploadValues that can send HTTP POST (or any kind of HTTP methods) AND handles the construction of request body (concatenating parameters with "&" and escaping characters by url encoding) in proper form data format:

using(WebClient client = new WebClient())
{
    var reqparm = new System.Collections.Specialized.NameValueCollection();
    reqparm.Add("param1", "<any> kinds & of = ? strings");
    reqparm.Add("param2", "escaping is already handled");
    byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
    string responsebody = Encoding.UTF8.GetString(responsebytes);
}

VBA - If a cell in column A is not blank the column B equals

If you really want a vba solution you can loop through a range like this:

Sub Check()
    Dim dat As Variant
    Dim rng As Range
    Dim i As Long

    Set rng = Range("A1:A100")
    dat = rng
    For i = LBound(dat, 1) To UBound(dat, 1)
        If dat(i, 1) <> "" Then
            rng(i, 2).Value = "My Text"
        End If
    Next
End Sub

*EDIT*

Instead of using varients you can just loop through the range like this:

Sub Check()
    Dim rng As Range
    Dim i As Long

    'Set the range in column A you want to loop through
    Set rng = Range("A1:A100")
    For Each cell In rng
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "My Text"
        End If
    Next
End Sub

Using a list as a data source for DataGridView

Set the DataGridView property

    gridView1.AutoGenerateColumns = true;

And make sure the list of objects your are binding, those object properties should be public.

How to insert a file in MySQL database?

File size by MySQL type:

  • TINYBLOB 255 bytes = 0.000255 Mb
  • BLOB 65535 bytes = 0.0655 Mb
  • MEDIUMBLOB 16777215 bytes = 16.78 Mb
  • LONGBLOB 4294967295 bytes = 4294.97 Mb = 4.295 Gb

Permission denied at hdfs

For Hadoop 3.x, if you try to create a file on HDFS when unauthenticated (e.g. user=dr.who) you will get this error.

It is not recommended for systems that need to be secure, however if you'd like to disable file permissions entirely in Hadoop 3 the hdfs-site.xml setting has changed to:

<property>
  <name>dfs.permissions.enabled</name>
  <value>false</value>
</property>

https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).

As others have said though, ATP should definitely not be turned off for production apps.

1) Use a different plist for Debug

Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.

XCode Debug

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

2) Exclude local servers

Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>server.local</key>
        <dict/>
        <key>NSExceptionAllowsInsecureHTTPLoads</key>
        <true/>
    </dict>
</dict>

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

How to set a transparent background of JPanel?

 public void paintComponent (Graphics g)
    { 
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.0f)); // draw transparent background
     super.paintComponent(g);
    ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); // turn on opacity
    g.setColor(Color.RED);
    g.fillRect(20, 20, 500, 300);
     } 

I have tried to do it this way, but it is very flickery

How to create a Rectangle object in Java using g.fillRect method

Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

public void drawRect(int x,
        int y,
        int width,
        int height)

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)

Double array initialization in Java

It is called an array initializer and can be explained in the Java specification 10.6.

This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.

Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.

React Native fixed footer

You get the Dimension first and then manipulate it through flex style

var Dimensions = require('Dimensions')
var {width, height} = Dimensions.get('window')

In render

<View style={{flex: 1}}>
    <View style={{width: width, height: height - 200}}>main</View>
    <View style={{width: width, height: 200}}>footer</View>
</View>

The other method is to use flex

<View style={{flex: 1}}>
    <View style={{flex: .8}}>main</View>
    <View style={{flex: .2}}>footer</View>
</View>

Psql could not connect to server: No such file or directory, 5432 error?

I occasionally have the same issue but mostly after macOS upgrades. Shutting down and migrating to the new version usually fixes it for me(make changes according to your version). So first upgrade your postgresql

brew services stop postgresql@12
brew services start postgresql@12
brew postgresql-upgrade-database

This is mostly a temporary fix but since I couldn't find a better solution this works for me.

Update: If the issue says that another postmaster is running then try removing it from that location(your postmaster.pid location will be displayed to you)

rm /usr/local/var/postgres/postmaster.pid

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

Performance differences between ArrayList and LinkedList

The ArrayList class is a wrapper class for an array. It contains an inner array.

public ArrayList<T> {
    private Object[] array;
    private int size;
}

A LinkedList is a wrapper class for a linked list, with an inner node for managing the data.

public LinkedList<T> {
    class Node<T> {
        T data;
        Node next;
        Node prev;
    }
    private Node<T> first;
    private Node<T> last;
    private int size;
}

Note, the present code is used to show how the class may be, not the actual implementation. Knowing how the implementation may be, we can do the further analysis:

ArrayList is faster than LinkedList if I randomly access its elements. I think random access means "give me the nth element". Why ArrayList is faster?

Access time for ArrayList: O(1). Access time for LinkedList: O(n).

In an array, you can access to any element by using array[index], while in a linked list you must navigate through all the list starting from first until you get the element you need.

LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.

Deletion time for ArrayList: Access time + O(n). Deletion time for LinkedList: Access time + O(1).

The ArrayList must move all the elements from array[index] to array[index-1] starting by the item to delete index. The LinkedList should navigate until that item and then erase that node by decoupling it from the list.

LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.

Insertion time for ArrayList: O(n). Insertion time for LinkedList: O(1).

Why the ArrayList can take O(n)? Because when you insert a new element and the array is full, you need to create a new array with more size (you can calculate the new size with a formula like 2 * size or 3 * size / 2). The LinkedList just add a new node next to the last.

This analysis is not just in Java but in another programming languages like C, C++ and C#.

More info here:

Ping site and return result in PHP

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}  

This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.

Convert Existing Eclipse Project to Maven Project

I was having the same issue and wanted to Mavenise entire eclipse workspace containing around 60 Eclipse projects. Doing so manually required a lot of time and alternate options were not that viable. To solve the issue I finally created a project called eclipse-to-maven on github. As eclipse doesn't have all necessary information about the dependencies, it does the following:

  • Based on <classpathentry/> XML elements in .classpath file, it creates the dependencies on another project, identifies the library jar file and based on its name (for instance jakarta-oro-2.0.8.jar) identifies its version. Currently artifactId and groupId are same as I couldn't find something which could return me the Maven groupId of the dependency based on artifactId. Though this is not a perfect solution it provides a good ground to speed up Mavenisation.

  • It moves all source folders according to Maven convention (like src/main/java)

  • As Eclipse projects having names with spaces are difficult to deal on Linux/Unix environment, it renames them as well with names without spaces.

  • Resultant pom.xml files contain the dependencies and basic pom structure. You have to add required Maven plugins manually.

What is the difference between docker-compose ports vs expose

I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:

Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.

This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.

Order by in Inner Join

I found this to be an issue when joining but you might find this blog useful in understanding how Joins work in the back. How Joins Work..

[Edited] @Shree Thank you for pointing that out. On the paragraph of Merge Join. It mentions on how joins work...

Like hash join, merge join consists of two steps. First, both tables of the join are sorted on the join attribute. This can be done with just two passes through each table via an external merge sort. Finally, the result tuples are generated as the next ordered element is pulled from each table and the join attributes are compared

.

Error message: "'chromedriver' executable needs to be available in the path"

Best way for sure is here:

Download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

You are done no need to add paths or anything

How to generate XML file dynamically using PHP?

I see examples with both DOM and SimpleXML, but none with the XMLWriter.

Please keep in mind that from the tests I've done, both DOM and SimpleXML are almost twice slower then the XMLWriter and for larger files you should consider using the later one.

Here's a full working example, clear and simple that meets the requirements, written with XMLWriter (I'm sure it will help other users):

// array with the key / value pairs of the information to be added (can be an array with the data fetched from db as well)
$songs = [
    'song1.mp3' => 'Track 1 - Track Title',
    'song2.mp3' => 'Track 2 - Track Title',
    'song3.mp3' => 'Track 3 - Track Title',
    'song4.mp3' => 'Track 4 - Track Title',
    'song5.mp3' => 'Track 5 - Track Title',
    'song6.mp3' => 'Track 6 - Track Title',
    'song7.mp3' => 'Track 7 - Track Title',
    'song8.mp3' => 'Track 8 - Track Title',
];

$xml = new XMLWriter();
$xml->openURI('songs.xml');
$xml->setIndent(true);
$xml->setIndentString('    ');
$xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('xml');
            foreach($songs as $song => $track){
                $xml->startElement('track');
                    $xml->writeElement('path', $song);
                    $xml->writeElement('title', $track);
                $xml->endElement();
            }
    $xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);

Purpose of a constructor in Java?

Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.

To understand clearly, see the below simple example:

class Student
{
    int sno,sage;
    String sname,dept;
    Student()
    {
        dept="CSE";
    }
    public static void main(String a[])
    {
        Student s1=new Student();
        s1.sno=101;
        s1.sage=33;
        s1.sname="John";

        Student s2=new Student();
        s2.sno=102;
        s2.sage=99;
        s2.sname="Peter";


        Student s3=new Student();
        s3.sno=102;
        s3.sage=99;
        s3.sname="Peter";
        System.out.println("The details of student1 are");
        System.out.println("The student no is:"+s1.sno);
        System.out.println("The student age is:"+s1.sage);
        System.out.println("The student name is:"+s1.sname);
        System.out.println("The student dept is:"+s1.dept);


        System.out.println("The details of student2 are");`enter code here`
        System.out.println("The student no is:"+s2.sno);
        System.out.println("The student age is:"+s2.sage);
        System.out.println("The student name is:"+s2.sname);
        System.out.println("The student dept is:"+s2.dept);

        System.out.println("The details of student2 are");
        System.out.println("The student no is:"+s3.sno);
        System.out.println("The student age is:"+s3.sage);
        System.out.println("The student name is:"+s3.sname);
        System.out.println("The student dept is:"+s3.dept);
    }
}

Output:

The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE

Update Git submodule to latest commit on origin

git pull --recurse-submodules

This will pull all the latest commits.

What does -save-dev mean in npm install grunt --save-dev

When you use the parameter "--save" your dependency will go inside the #1 below in package.json. When you use the parameter "--save-dev" your dependency will go inside the #2 below in package.json.

#1. "dependencies": these packages are required by your application in production.

#2. "devDependencies": these packages are only needed for development and testing

How to clean old dependencies from maven repositories?

Short answer - Deleted .m2 folder in {user.home}. E.g. in windows 10 user home is C:\Users\user1. Re-build your project using mvn clean package. Only those dependencies would remain, which are required by the projects.

Long Answer - .m2 folder is just like a normal folder and the content of the folder is built from different projects. I think there is no way to figure out automatically that which library is "old". In fact old is a vague word. There could be so many reasons when a previous version of a library is used in a project, hence determining which one is unused is not possible.

All you could do, is to delete the .m2 folder and re-build all of your projects and then the folder would automatically build with all the required library.

If you are concern about only a particular version of a library to be used in all the projects; it is important that the project's pom should also update to latest version. i.e. if different POMs refer different versions of the library, all will get downloaded in .m2.

How do I display images from Google Drive on a website?

Extension of the above-mentioned answer. I wrote a UNIX command so I can easily do it in my workflow.

  1. Copy the Google Drive photos URL which needs to be converted. E.g.

Copy Google Drive Image URL

https://drive.google.com/file/d/XXXX/view?usp=sharing
  1. Open the terminal and execute this command.

Command:

echo https://drive.google.com/uc\?export\=view\&id\=`echo $(pbpaste) | cut -d '/' -f 6`

Output:

https://drive.google.com/uc?export=view&id=XXXX

P.S. If you copy the command from here. Make sure to copy the Google Drive image URL again. :P

No need to change anything in the Step 2 command as it takes from Clipboard. Make sure it is copied in right format E.g. https://drive.google.com/file/d/XXXX/view?usp=sharing

In Powershell what is the idiomatic way of converting a string to an int?

For me $numberAsString -as [int] of @Shay Levy is the best practice, I also use [type]::Parse(...) or [type]::TryParse(...)

But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an Int32:

PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

You can use Exception (try/parse) to behave in case of Problem

How to apply a CSS filter to a background image

Check out this pen.

You will have to use two different containers, one for the background image and the other for your content.

In the example, I have created two containers, .background-image and .content.

Both of them are placed with position: fixed and left: 0; right: 0;. The difference in displaying them comes from the z-index values which have been set differently for the elements.

_x000D_
_x000D_
.background-image {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 1;
  display: block;
  background-image: url('https://i.imgur.com/lL6tQfy.png');
  width: 1200px;
  height: 800px;
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

.content {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 9999;
  margin-left: 20px;
  margin-right: 20px;
}
_x000D_
<div class="background-image"></div>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam erat in ante malesuada, facilisis semper nulla semper. Phasellus sapien neque, faucibus in malesuada quis, lacinia et libero. Sed sed turpis tellus. Etiam ac aliquam tortor, eleifend
    rhoncus metus. Ut turpis massa, sollicitudin sit amet molestie a, posuere sit amet nisl. Mauris tincidunt cursus posuere. Nam commodo libero quis lacus sodales, nec feugiat ante posuere. Donec pulvinar auctor commodo. Donec egestas diam ut mi adipiscing,
    quis lacinia mauris condimentum. Quisque quis odio venenatis, venenatis nisi a, vehicula ipsum. Etiam at nisl eu felis vulputate porta.</p>
  <p>Fusce ut placerat eros. Aliquam consequat in augue sed convallis. Donec orci urna, tincidunt vel dui at, elementum semper dolor. Donec tincidunt risus sed magna dictum, quis luctus metus volutpat. Donec accumsan et nunc vulputate accumsan. Vestibulum
    tempor, erat in mattis fringilla, elit urna ornare nunc, vel pretium elit sem quis orci. Vivamus condimentum dictum tempor. Nam at est ante. Sed lobortis et lorem in sagittis. In suscipit in est et vehicula.</p>
</div>
_x000D_
_x000D_
_x000D_

Apologies for the Lorem Ipsum text.

Update

Thanks to Matthew Wilcoxson for a better implementation using .content::before https://codepen.io/akademy/pen/FlkzB

Android: Cancel Async Task

I spent a while figuring this out, all I wanted was a simple example of how to do it, so I thought I'd post how I did it. This is some code that updates a library and has a progress dialog showing how many books have been updated and cancels when a user dismisses the dialog:

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else 
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY,Str.TEXT_NOUPDATE , Library.instance);
    }
}

Difference between hamiltonian path and euler path

Euler Path - An Euler path is a path in which each edge is traversed exactly once.

Hamiltonian Path - An Hamiltonian path is path in which each vertex is traversed exactly once.

If you have ever confusion remember E - Euler E - Edge.

Read and overwrite a file in Python

If you don't want to close and reopen the file, to avoid race conditions, you could truncate it:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

The functionality will likely also be cleaner and safer using open as a context manager, which will close the file handler, even if an error occurs!

with open(filename, 'r+') as f:
    text = f.read()
    text = re.sub('foobar', 'bar', text)
    f.seek(0)
    f.write(text)
    f.truncate()

Difference between return and exit in Bash functions

return will cause the current function to go out of scope, while exit will cause the script to end at the point where it is called. Here is a sample program to help explain this:

#!/bin/bash

retfunc()
{
    echo "this is retfunc()"
    return 1
}

exitfunc()
{
    echo "this is exitfunc()"
    exit 1
}

retfunc
echo "We are still here"
exitfunc
echo "We will never see this"

Output

$ ./test.sh
this is retfunc()
We are still here
this is exitfunc()

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

Try to remove armv7s from project's "Valid architecture" to release from this issue for iOS 5.1 phone

C++ Returning reference to local variable

A good thing to remember are these simple rules, and they apply to both parameters and return types...

  • Value - makes a copy of the item in question.
  • Pointer - refers to the address of the item in question.
  • Reference - is literally the item in question.

There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

void func1(int& oValue)
{
    oValue = 1;
}

Doing so would directly change the value of your passed in parameter. Whereas this code...

void func1(int oValue)
{
    oValue = 1;
}

would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

What does "Changes not staged for commit" mean

Suposed you saved a new file changes. (navbar.component.html for example)

Run:

ng status
modified:   src/app/components/shared/navbar/navbar.component.html

If you want to upload those changes for that file you must run:

git add src/app/components/shared/navbar/navbar.component.html

And then:

git commit src/app/components/shared/navbar/navbar.component.html -m "new navbar changes and fixes"

And then:

git push origin [your branch name, usually "master"]

---------------------------------------------------------------

Or if you want to upload all your changes (several/all files):

git commit -a

And them this will appear "Please enter the commit message for your changes."

  • You'll see this message if you git commit without a message (-m)
  • You can get out of it with two steps:
  • 1.a. Type a multi-line message to move foward with the commit.
  • 1.b. Leave blank to abort the commit.
    1. Hit "esc" then type ":wq" and hit enter to save your choice. Viola!

And then:

git push

And Viola!

Questions every good .NET developer should be able to answer?

I'm a fan of the following in addition to some of the questions already mentioned:

  • What's a delegate?
  • What's the app domain?
  • When would you use the lock keyword?
  • Are the standard library generic collection classes thread safe?
  • What's an extension method?
  • What's the difference between XmlDocument and XmlReader ?
  • How do you read in configuration settings from the application config file?

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. (Read More)

ExecuteScalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. It’s very fast to retrieve single values from database. (Read More)

ExecuteReader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last. (Read More)

Best way to encode text data for XML

XmlTextWriter.WriteString() does the escaping.

Getting value from table cell in JavaScript...not jQuery

Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:

alert(col.firstChild.value);

Mythical man month 10 lines per developer day - how close on large projects?

I think the number of lines added is highly dependent upon the state of the project, the rate of adding to a new project will be much higher than the rate of a starting project.

The work is different between the two - at a large project you usually spend most of the time figuring the relationships between the parts, and only a small amount to actually changing/adding. whereas in a new project - you mostly write... until it's big enough and the rate decreases.

Can I get all methods of a class?

package tPoint;

import java.io.File;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class ReadClasses {

public static void main(String[] args) {

    try {
        Class c = Class.forName("tPoint" + ".Sample");
        Object obj = c.newInstance();
        Document doc = 
        DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File("src/datasource.xml"));

        Method[] m = c.getDeclaredMethods();

        for (Method e : m) {
            String mName = e.getName();
            if (mName.startsWith("set")) {
                System.out.println(mName);
                e.invoke(obj, new 
          String(doc.getElementsByTagName(mName).item(0).getTextContent()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Function to check if a string is a date

In my project this seems to work:

function isDate($value) {
    if (!$value) {
        return false;
    } else {
        $date = date_parse($value);
        if($date['error_count'] == 0 && $date['warning_count'] == 0){
            return checkdate($date['month'], $date['day'], $date['year']);
        } else {
            return false;
        }
    }
}

Else clause on Python while statement

The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).

So the output would be this:

5
4
3
2
1
what the...

Split an NSString to access one particular piece

Use [myString componentsSeparatedByString:@"/"]

How can I export data to an Excel file

I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV, then opened the .CSV in Excel. This has its own problems, but I've found this the quickest method.

First, convert the .CSV:

// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
    // Get the bounds.
    var rows = Data[0].Count;
    var cols = Data.Count;
    var row = 0;

    // Convert the array into a CSV string.
    StringBuilder sb = new StringBuilder();

    // Add the first field in this row.
    sb.Append(Headers[0]);

    // Add the other fields in this row separated by commas.
    for (int col = 1; col < cols; col++)
        sb.Append("," + Headers[col]);

    // Move to the next line.
    sb.AppendLine();

    for (row = 0; row < rows; row++)
    {
        // Add the first field in this row.
        sb.Append(Data[0][row]);

        // Add the other fields in this row separated by commas.
        for (int col = 1; col < cols; col++)
            sb.Append("," + Data[col][row]);

        // Move to the next line.
        sb.AppendLine();
    }

    // Return the CSV format string.
    return sb.ToString();
}

Then, export it to Excel:

public void ExportToExcel()
{
    // Initialize app and pop Excel on the screen.
    var excelApp = new Excel.Application { Visible = true };

    // I use unix time to give the files a unique name that's almost somewhat useful.
    DateTime dateTime = DateTime.UtcNow;
    long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
    var path = @"C:\Users\my\path\here + unixTime + ".csv";

    var csv = GetCSV();
    File.WriteAllText(path, csv);

    // Create a new workbook and get its active sheet.
    excelApp.Workbooks.Open(path);

    var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

    // iterate over each value and throw it in the chart
    for (var column = 0; column < Data.Count; column++)
    {
        ((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
    }

    currentSheet = workSheet;
}

You'll have to install some stuff, too...

  1. Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel

  2. It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.

In case I forgot anything, here's my 'using' statements:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

Get div to take up 100% body height, minus fixed-height header and footer

As far as it is not cross browser solution, you might be take advantage of using calc(expression) to achive that.

html, body { 
 height: 100%;
}
header {        
 height: 50px;
 background-color: tomato
}

#content { 
 height: -moz-calc(100% - 100px); /* Firefox */
 height: -webkit-calc(100% - 100px); /* Chrome, Safari */
 height: calc(100% - 100px); /* IE9+ and future browsers */
 background-color: yellow 
}
footer { 
 height: 50px;
 background-color: grey;
}

Example at JsFiddle

If you want to know more about calc(expression) you'd better to visit this site.

What is JavaScript's highest integer value that a number can go to without losing precision?

Let's get to the sources

Description

The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2^53 - 1) and 2^53 - 1.

Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

Because MAX_SAFE_INTEGER is a static property of Number, you always use it as Number.MAX_SAFE_INTEGER, rather than as a property of a Number object you created.

Browser compatibility

enter image description here

SQL Server String or binary data would be truncated

This error is thrown when the column of a table puts constraint [ mostly length ]. . E.g. if database schema for column myColumn is CHAR(2), then when your call from any of your application to insert value, you must pass String of length two.

The error basically says it; string of length three and above is inconsistent to fit the length restriction specified by database schema. That's why SQL Server warns and throws data loss/ Truncation error.

What's the difference between session.persist() and session.save() in Hibernate?

It completely answered on basis of "generator" type in ID while storing any entity. If value for generator is "assigned" which means you are supplying the ID. Then it makes no diff in hibernate for save or persist. You can go with any method you want. If value is not "assigned" and you are using save() then you will get ID as return from the save() operation.

Another check is if you are performing the operation outside transaction limit or not. Because persist() belongs to JPA while save() for hibernate. So using persist() outside transaction boundaries will not allow to do so and throw exception related to persistant. while with save() no such restriction and one can go with DB transaction through save() outside the transaction limit.

Checkboxes in web pages – how to make them bigger?

Pure modern 2020 CSS only decision, without blurry scaling or non-handy transforming. And with tick! =)

Works nice in Firefox and Chromium-based browsers.

So, you can rule your checkboxes purely ADAPTIVE, just by setting parent block's font-height and it will grow with text!

_x000D_
_x000D_
input[type='checkbox'] {_x000D_
  -moz-appearance: none;_x000D_
  -webkit-appearance: none;_x000D_
  appearance: none;_x000D_
  vertical-align: middle;_x000D_
  outline: none;_x000D_
  font-size: inherit;_x000D_
  cursor: pointer;_x000D_
  width: 1.0em;_x000D_
  height: 1.0em;_x000D_
  background: white;_x000D_
  border-radius: 0.25em;_x000D_
  border: 0.125em solid #555;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type='checkbox']:checked {_x000D_
  background: #adf;_x000D_
}_x000D_
_x000D_
input[type='checkbox']:checked:after {_x000D_
  content: "?";_x000D_
  position: absolute;_x000D_
  font-size: 90%;_x000D_
  left: 0.0625em;_x000D_
  top: -0.25em;_x000D_
}
_x000D_
<label for="check1"><input type="checkbox" id="check1" checked="checked" /> checkbox one</label>_x000D_
<label for="check2"><input type="checkbox" id="check2" /> another checkbox</label>
_x000D_
_x000D_
_x000D_

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I've ran into this exact problem. The heap is pretty small so these images can get out of control rather quickly in regards to memory. One way is to give the garbage collector a hint to collect memory on a bitmap by calling its recycle method.

Also, the onDestroy method is not guaranteed to get called. You may want to move this logic/clean up into the onPause activity. Check out the Activity Lifecycle diagram/table on this page for more info.

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange.

UsedRange is highly unreliable as shown HERE

To find the last column which has data, use .Find and then subtract from it.

With Sheets("Sheet1")
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastCol = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Column
    Else
        lastCol = 1
    End If
End With

If lastCol > 8 Then
    'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8

    'The above becomes

    Debug.Print lastCol - 8
End If

How to print pandas DataFrame without index

print(df.to_csv(sep='\t', index=False))

Or possibly:

print(df.to_csv(columns=['A', 'B', 'C'], sep='\t', index=False))

Rotate axis text in python matplotlib

My answer is inspired by cjohnson318's answer, but I didn't want to supply a hardcoded list of labels; I wanted to rotate the existing labels:

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

android TextView: setting the background color dynamically doesn't work

Well I had situation when web service returned a color in hex format like "#CC2233" and I wanted to put this color on textView by using setBackGroundColor(), so I used android Color class to get int value of hex string and passed it to mentioned function. Everything worked. This is example:

String myHexColor = "#CC2233";
TextView myView = (TextView) findViewById(R.id.myTextView);
myView.setBackGroundColor(Color.pasrsehexString(myHexColor));

P.S. posted this answer because other solutions didn't work for me. I hope this will help someone:)

Copy array by value

There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:

var arr1 = [1, 2, 3];
console.log(Array.from(arr1)); // Logs: [1, 2, 3]

Reference: Here

Or Array.prototype.map may be used with an identity function:

function identity(param)
{
    return param;
}

var arr1 = [1, 2, 3],
    clone = arr1.map(identity);

Reference: Here

UIImageView - How to get the file name of the image assigned?

if ([imageForCheckMark.image isEqual:[UIImage imageNamed:@"crossCheckMark.png"]]||[imageForCheckMark.image isEqual:[UIImage imageNamed:@"checkMark.png"]])
{

}

Java: Convert String to TimeStamp

can you try it once...

String dob="your date String";
String dobis=null;
final DateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
final Calendar c = Calendar.getInstance();
try {
    if(dob!=null && !dob.isEmpty() && dob != "")
    {
    c.setTime(df.parse(dob));
    int month=c.get(Calendar.MONTH);
    month=month+1;
    dobis=c.get(Calendar.YEAR)+"-"+month+"-"+c.get(Calendar.DAY_OF_MONTH);
    }

}

Tracking Google Analytics Page Views with AngularJS

Merging even more with Pedro Lopez's answer,

I added this to my ngGoogleAnalytis module(which I reuse in many apps):

var base = $('base').attr('href').replace(/\/$/, "");

in this case, I have a tag in my index link:

  <base href="/store/">

it's useful when using html5 mode on angular.js v1.3

(remove the replace() function call if your base tag doesn't finish with a slash /)

angular.module("ngGoogleAnalytics", []).run(['$rootScope', '$location', '$window',
    function($rootScope, $location, $window) {
      $rootScope.$on('$routeChangeSuccess',
        function(event) {
          if (!$window.ga) { return; }
          var base = $('base').attr('href').replace(/\/$/, "");

          $window.ga('send', 'pageview', {
            page: base + $location.path()
          });
        }
      );
    }
  ]);

Serializing to JSON in jQuery

One thing that the above solutions don't take into account is if you have an array of inputs but only one value was supplied.

For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. Then doing:

<input type="hidden" name="People" value="Joe" />

Then with the previous solutions, it would just map to something like:

{
    "People" : "Joe"
}

But it should really map to

{
    "People" : [ "Joe" ]
}

To fix that, the input should look like:

<input type="hidden" name="People[]" value="Joe" />

And you would use the following function (based off of other solutions, but extended a bit)

$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if (this.name.substr(-2) == "[]"){
        this.name = this.name.substr(0, this.name.length - 2);
        o[this.name] = [];
    }

    if (o[this.name]) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

com.jcraft.jsch.JSchException: UnknownHostKey

It is a security risk to avoid host key checking.

JSch uses HostKeyRepository interface and its default implementation KnownHosts class to manage this. You can provide an alternate implementation that allows specific keys by implementing HostKeyRepository. Or you could keep the keys that you want to allow in a file in the known_hosts format and call

jsch.setKnownHosts(knownHostsFileName);

Or with a public key String as below.

String knownHostPublicKey = "mysite.com ecdsa-sha2-nistp256 AAAAE............/3vplY";
jsch.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

see Javadoc for more details.

This would be a more secure solution.

Jsch is open source and you can download the source from here. In the examples folder, look for KnownHosts.java to know more details.

Binding Combobox Using Dictionary as the Datasource

A dictionary cannot be directly used as a data source, you should do more.

SortedDictionary<string, int> userCache =  UserCache.getSortedUserValueCache();
KeyValuePair<string, int> [] ar= new KeyValuePair<string,int>[userCache.Count];
userCache.CopyTo(ar, 0);
comboBox1.DataSource = ar; new BindingSource(ar, "Key"); //This line is causing the error
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

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

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

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

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


align="center" has no effect.

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

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

What is the meaning of "Failed building wheel for X" in pip install?

I got the same message when I tried to install pip install django-imagekit. So I ran pip install wheel (I had python 2.7) and then I reran pip install django-imagekit and it worked. Thanks

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

Actually it is the issue related to the app store. I have upload many build some time it takes time depend upon the size of the ipa and at which time you are uploading it to the App Store. Please use Application Loader 3.0 or higher to upload the build.

Run Command Prompt Commands

with a reference to Microsoft.VisualBasic

Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);

How to convert a Drawable to a Bitmap?

A Drawable can be drawn onto a Canvas, and a Canvas can be backed by a Bitmap:

(Updated to handle a quick conversion for BitmapDrawables and to ensure that the Bitmap created has a valid size)

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Connect to mysql on Amazon EC2 from a remote server

Change /etc/mysql/my.cnf:

bind-address            = 127.0.0.1 to 0.0.0.0

Create user with '%' host and restart:

/etc/init.d/mysql restart

Works for me! :)

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

You may not find this in any book or site but I found out that it works pretty well:

ifstream ifs ("filename.txt");
string s;
getline (ifs, s, (char) ifs.eof());

codeigniter, result() vs. result_array()

Result has an optional $type parameter which decides what type of result is returned. By default ($type = "object"), it returns an object (result_object()). It can be set to "array", then it will return an array of result, that being equivalent of caling result_array(). The third version accepts a custom class to use as a result object.

The code from CodeIgniter:

/**
* Query result. Acts as a wrapper function for the following functions.
*
* @param string $type 'object', 'array' or a custom class name
* @return array
*/
public function result($type = 'object')
{
    if ($type === 'array')
    {
        return $this->result_array();
    }
    elseif ($type === 'object')
    {
        return $this->result_object();
    }
    else
    {
        return $this->custom_result_object($type);
    }
}

Arrays are technically faster, but they are not objects. It depends where do you want to use the result. Most of the time, arrays are sufficient.

MySQL load NULL values from CSV data

MySQL manual says:

When reading data with LOAD DATA INFILE, empty or missing columns are updated with ''. If you want a NULL value in a column, you should use \N in the data file. The literal word “NULL” may also be used under some circumstances.

So you need to replace the blanks with \N like this:

1,2,3,4,5
1,2,3,\N,5
1,2,3

Why use @PostConstruct?

The main problem is that:

in a constructor, the injection of the dependencies has not yet occurred*

*obviously excluding Constructor Injection


Real-world example:

public class Foo {

    @Inject
    Logger LOG;

    @PostConstruct
    public void fooInit(){
        LOG.info("This will be printed; LOG has already been injected");
    }

    public Foo() {
        LOG.info("This will NOT be printed, LOG is still null");
        // NullPointerException will be thrown here
    }
}

IMPORTANT: @PostConstruct and @PreDestroy have been completely removed in Java 11.

To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.

Maven

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

Gradle

// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'

Push Notifications in Android Platform

You can use Xtify (http://developer.xtify.com) - they have a push notifications webservice that works with their SDK. it's free and so far, it's worked really well for me.

How do I parse a string into a number with Dart?

Convert String to Int

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);

Convert String to Double

var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);

Example in DartPad

screenshot of dartpad

How to avoid Python/Pandas creating an index in a saved csv?

If you want no index, read file using:

import pandas as pd
df = pd.read_csv('file.csv', index_col=0)

save it using

df.to_csv('file.csv', index=False)

Handling JSON Post Request in Go

I found the following example from the docs really helpful (source here).

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "strings"
)

func main() {
    const jsonStream = `
        {"Name": "Ed", "Text": "Knock knock."}
        {"Name": "Sam", "Text": "Who's there?"}
        {"Name": "Ed", "Text": "Go fmt."}
        {"Name": "Sam", "Text": "Go fmt who?"}
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    `
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))
    for {
        var m Message
        if err := dec.Decode(&m); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s: %s\n", m.Name, m.Text)
    }
}

The key here being that the OP was looking to decode

type test_struct struct {
    Test string
}

...in which case we would drop the const jsonStream, and replace the Message struct with the test_struct:

func test(rw http.ResponseWriter, req *http.Request) {
    dec := json.NewDecoder(req.Body)
    for {
        var t test_struct
        if err := dec.Decode(&t); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        log.Printf("%s\n", t.Test)
    }
}

Update: I would also add that this post provides some great data about responding with JSON as well. The author explains struct tags, which I was not aware of.

Since JSON does not normally look like {"Test": "test", "SomeKey": "SomeVal"}, but rather {"test": "test", "somekey": "some value"}, you can restructure your struct like this:

type test_struct struct {
    Test string `json:"test"`
    SomeKey string `json:"some-key"`
}

...and now your handler will parse JSON using "some-key" as opposed to "SomeKey" (which you will be using internally).

Replace specific characters within strings

      library(stringi)

            group <- c('12357e', '12575e', '12575e', ' 197e18',  'e18947')

            pattern <- "e"  
            replacement <-  ""  
            group <- str_replace(group, pattern, replacement)      
            group    

[1] "12357"  "12575"  "12575"  " 19718" "18947" 

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Your second example does not work if you send the argument by reference. Did you mean

void copyVecFast(vec<int> original) // no reference
{

  vector<int> new_;
  new_.swap(original); 
}

That would work, but an easier way is

vector<int> new_(original);

Logger slf4j advantages of formatting with {} instead of string concatenation

Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.

How to remove element from ArrayList by checking its value?

use contains() method which is available in list interface to check the value exists in list or not.If it contains that element, get its index and remove it

Center Oversized Image in Div

This is an old Q, but a modern solution without flexbox or position absolute works like this.

margin-left: 50%;
transform: translateX(-50%);

_x000D_
_x000D_
.outer {_x000D_
  border: 1px solid green;_x000D_
  margin: 20px auto;_x000D_
  width: 20%;_x000D_
  padding: 10px 0;_x000D_
  /*   overflow: hidden; */_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  width: 150%;_x000D_
  background-color: gold;_x000D_
  /* Set left edge of inner element to 50% of the parent element */_x000D_
  margin-left: 50%; _x000D_
  /* Move to the left by 50% of own width */_x000D_
  transform: translateX(-50%); _x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.

We have this situation before we add the CSS

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       +-----------------------------------------------------------+
       | Element E                                                 |
       +-----------------------------------------------------------+
       |                                           |
       +-------------------------------------------+

With the added style margin-left: 50% we have

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       |                     +-----------------------------------------------------------+
       |                     | Element E                                                 |
       |                     +-----------------------------------------------------------+
       |                     |                     |
       +---------------------|---------------------+
       |========= a ========>|

       a is 50% width of P

And the transform: translateX(-50%) shifts back to the left

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
+-----------------------------------------------------------+
| Element E                 |                               |
+-----------------------------------------------------------+
|<============ b ===========|                      |
       |                    |                      |
       +--------------------|----------------------+
       |========= a =======>|

       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d

How can I control the speed that bootstrap carousel slides in items?

To complement the previous answers, after you edit your CSS file, you just need to edit CAROUSEL.TRANSITION_DURATION (in bootstrap.js) or c.TRANSITION_DURATION (if you use bootstrap.min.js) and to change the value inside it (600 for default). The final value must be the same that you put in your CSS file (for example, 10s in CSS = 10000 in .js)

Carousel.VERSION  = '3.3.2'
Carousel.TRANSITION_DURATION = xxxxx /* Your number here*/
Carousel.DEFAULTS = {
interval: 5000 /* you could change this value too, but to add data-interval="xxxx" to your html it's fine too*/
pause: 'hover',
wrap: true,
keyboard: true
}

How to prevent robots from automatically filling up a form?

the easy way i found to do this is to put a field with a value and ask the user to remove the text in this field. since bots only fill them up. if the field is not empty it means that the user is not human and it wont be posted. its the same purpose of a captcha code.

Classes vs. Functions

Never create classes. At least the OOP kind of classes in Python being discussed.

Consider this simplistic class:

class Person(object):
    def __init__(self, id, name, city, account_balance):
        self.id = id
        self.name = name
        self.city = city
        self.account_balance = account_balance

    def adjust_balance(self, offset):
        self.account_balance += offset


if __name__ == "__main__":
    p = Person(123, "bob", "boston", 100.0)
    p.adjust_balance(50.0)
    print("done!: {}".format(p.__dict__))

vs this namedtuple version:

from collections import namedtuple

Person = namedtuple("Person", ["id", "name", "city", "account_balance"])


def adjust_balance(person, offset):
    return person._replace(account_balance=person.account_balance + offset)


if __name__ == "__main__":
    p = Person(123, "bob", "boston", 100.0)
    p = adjust_balance(p, 50.0)
    print("done!: {}".format(p))

The namedtuple approach is better because:

  • namedtuples have more concise syntax and standard usage.
  • In terms of understanding existing code, namedtuples are basically effortless to understand. Classes are more complex. And classes can get very complex for humans to read.
  • namedtuples are immutable. Managing mutable state adds unnecessary complexity.
  • class inheritance adds complexity, and hides complexity.

I can't see a single advantage to using OOP classes. Obviously, if you are used to OOP, or you have to interface with code that requires classes like Django.

BTW, most other languages have some record type feature like namedtuples. Scala, for example, has case classes. This logic applies equally there.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

The issue is caused by either one of two things :-

  1. You tried to update a row with one or more properties are Concurrency Mode: Fixed .. and the Optimistic Concurrency prevented the data from being saved. Ie. some changed the row data between the time you received the server data and when you saved your server data.
  2. You tried to update or delete a row but the row doesn't exist. Another example of someone changing the data (in this case, removing) in between a retrieve then save OR you're flat our trying to update a field which is not an Identity (ie. StoreGeneratedPattern = Computed) and that row doesn't exist.

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

Android SeekBar setOnSeekBarChangeListener

All answers are correct, but you need to convert a long big fat number into a timer first:

    public String toTimer(long milliseconds){
    String finalTimerString = "";
    String secondsString;
    // Convert total duration into time
    int hours = (int)( milliseconds / (1000*60*60));
    int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
    int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
    // Add hours if there
    if(hours > 0){
        finalTimerString = hours + ":";
    }
    // Prepending 0 to seconds if it is one digit
    if(seconds < 10){
        secondsString = "0" + seconds;
    }else{
        secondsString = "" + seconds;}
    finalTimerString = finalTimerString + minutes + ":" + secondsString;
    // return timer string
    return finalTimerString;
}

And this is how you use it:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));        
}

Find the division remainder of a number

We can solve this by using modulus operator (%)

26 % 7 = 5;

but 26 / 7 = 3 because it will give quotient but % operator will give remainder.

Read next word in java

You already get the next line in this line of your code:

 String line = sc.nextLine();  

To get the words of a line, I would recommend to use:

String[] words = line.split(" ");

How do I jump to a closing bracket in Visual Studio Code?

The 'go to bracket' shortcut takes cursor before the bracket, unlike the 'end' key which takes after the bracket. WASDMap VSCode extension is very helpful for navigating and selecting text using WASD keys.

Connecting to Oracle Database through C#?

First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

After installation add a reference of the assembly Oracle.DataAccess.dll.

Your are good to go after this.

using System; 
using Oracle.DataAccess.Client; 

class OraTest
{ 
    OracleConnection con; 
    void Connect() 
    { 
        con = new OracleConnection(); 
        con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>"; 
        con.Open(); 
        Console.WriteLine("Connected to Oracle" + con.ServerVersion); 
    }

    void Close() 
    {
        con.Close(); 
        con.Dispose(); 
    } 

    static void Main() 
    { 
        OraTest ot= new OraTest(); 
        ot.Connect(); 
        ot.Close(); 
    } 
}

TreeMap sort by value

import java.util.*;

public class Main {

public static void main(String[] args) {
    TreeMap<String, Integer> initTree = new TreeMap();
    initTree.put("D", 0);
    initTree.put("C", -3);
    initTree.put("A", 43);
    initTree.put("B", 32);
    System.out.println("Sorted by keys:");
    System.out.println(initTree);
    List list = new ArrayList(initTree.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
            return e1.getValue().compareTo(e2.getValue());
        }
    });
    System.out.println("Sorted by values:");
    System.out.println(list);
}
}

Duplicate headers received from server

For me the issue was about a comma not in the filename but as below: -

Response.ok(streamingOutput,MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment, filename=your_file_name").build();

I accidentally put a comma after attachment. Got it resolved by replacing comma with a semicolon.

How to hide element label by element id in CSS?

This is worked for me.

#_account_id{
        display: none;
    }
    label[for="_account_id"] { display: none !important; }

How to find out the username and password for mysql database

In your local system right,

   go to this url : http://localhost/phpmyadmin/

   In this click mysql default db, after that browser user table to get existing username and password.

What's the fastest way of checking if a point is inside a polygon in python

Comparison of different methods

I found other methods to check if a point is inside a polygon (here). I tested two of them only (is_inside_sm and is_inside_postgis) and the results were the same as the other methods.

Thanks to @epifanio, I parallelized the codes and compared them with @epifanio and @user3274748 (ray_tracing_numpy) methods. Note that both methods had a bug so I fixed them as shown in their codes below.

One more thing that I found is that the code provided for creating a polygon does not generate a closed path np.linspace(0,2*np.pi,lenpoly)[:-1]. As a result, the codes provided in above GitHub repository may not work properly. So It's better to create a closed path (first and last points should be the same).

Codes

Method 1: parallelpointinpolygon

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):   #<-- Fixed here, must start from zero
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D  

Method 2: ray_tracing_numpy_numba

@jit(nopython=True)
def ray_tracing_numpy_numba(points,poly):
    x,y = points[:,0], points[:,1]
    n = len(poly)
    inside = np.zeros(len(x),np.bool_)
    p2x = 0.0
    p2y = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        idx = np.nonzero((y > min(p1y,p2y)) & (y <= max(p1y,p2y)) & (x <= max(p1x,p2x)))[0]
        if len(idx):    # <-- Fixed here. If idx is null skip comparisons below.
            if p1y != p2y:
                xints = (y[idx]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
            if p1x == p2x:
                inside[idx] = ~inside[idx]
            else:
                idxx = idx[x[idx] <= xints]
                inside[idxx] = ~inside[idxx]    

        p1x,p1y = p2x,p2y
    return inside 

Method 3: Matplotlib contains_points

path = mpltPath.Path(polygon,closed=True)  # <-- Very important to mention that the path 
                                           #     is closed (default is false)

Method 4: is_inside_sm (got it from here)

@jit(nopython=True)
def is_inside_sm(polygon, point):
    length = len(polygon)-1
    dy2 = point[1] - polygon[0][1]
    intersections = 0
    ii = 0
    jj = 1

    while ii<length:
        dy  = dy2
        dy2 = point[1] - polygon[jj][1]

        # consider only lines which are not completely above/bellow/right from the point
        if dy*dy2 <= 0.0 and (point[0] >= polygon[ii][0] or point[0] >= polygon[jj][0]):

            # non-horizontal line
            if dy<0 or dy2<0:
                F = dy*(polygon[jj][0] - polygon[ii][0])/(dy-dy2) + polygon[ii][0]

                if point[0] > F: # if line is left from the point - the ray moving towards left, will intersect it
                    intersections += 1
                elif point[0] == F: # point on line
                    return 2

            # point on upper peak (dy2=dx2=0) or horizontal line (dy=dy2=0 and dx*dx2<=0)
            elif dy2==0 and (point[0]==polygon[jj][0] or (dy==0 and (point[0]-polygon[ii][0])*(point[0]-polygon[jj][0])<=0)):
                return 2

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections & 1  


@njit(parallel=True)
def is_inside_sm_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_sm(polygon,points[i])
    return D  

Method 5: is_inside_postgis (got it from here)

@jit(nopython=True)
def is_inside_postgis(polygon, point):
    length = len(polygon)
    intersections = 0

    dx2 = point[0] - polygon[0][0]
    dy2 = point[1] - polygon[0][1]
    ii = 0
    jj = 1

    while jj<length:
        dx  = dx2
        dy  = dy2
        dx2 = point[0] - polygon[jj][0]
        dy2 = point[1] - polygon[jj][1]

        F =(dx-dx2)*dy - dx*(dy-dy2);
        if 0.0==F and dx*dx2<=0 and dy*dy2<=0:
            return 2;

        if (dy>=0 and dy2<0) or (dy2>=0 and dy<0):
            if F > 0:
                intersections += 1
            elif F < 0:
                intersections -= 1

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections != 0  


@njit(parallel=True)
def is_inside_postgis_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_postgis(polygon,points[i])
    return D  

Benchmark

enter image description here

Timing for 10 million points:

parallelpointinpolygon Elapsed time:      4.0122294425964355
Matplotlib contains_points Elapsed time: 14.117807388305664
ray_tracing_numpy_numba Elapsed time:     7.908452272415161
sm_parallel Elapsed time:                 0.7710440158843994
is_inside_postgis_parallel Elapsed time:  2.131121873855591

Here is the code.

import matplotlib.pyplot as plt
import matplotlib.path as mpltPath
from time import time
import numpy as np

np.random.seed(2)

time_parallelpointinpolygon=[]
time_mpltPath=[]
time_ray_tracing_numpy_numba=[]
time_is_inside_sm_parallel=[]
time_is_inside_postgis_parallel=[]
n_points=[]

for i in range(1, 10000002, 1000000): 
    n_points.append(i)
    
    lenpoly = 100
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    N = i
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))
    
    
    #Method 1
    start_time = time()
    inside1=parallelpointinpolygon(points, polygon)
    time_parallelpointinpolygon.append(time()-start_time)

    # Method 2
    start_time = time()
    path = mpltPath.Path(polygon,closed=True)
    inside2 = path.contains_points(points)
    time_mpltPath.append(time()-start_time)

    # Method 3
    start_time = time()
    inside3=ray_tracing_numpy_numba(points,polygon)
    time_ray_tracing_numpy_numba.append(time()-start_time)

    # Method 4
    start_time = time()
    inside4=is_inside_sm_parallel(points,polygon)
    time_is_inside_sm_parallel.append(time()-start_time)

    # Method 5
    start_time = time()
    inside5=is_inside_postgis_parallel(points,polygon)
    time_is_inside_postgis_parallel.append(time()-start_time)


    
plt.plot(n_points,time_parallelpointinpolygon,label='parallelpointinpolygon')
plt.plot(n_points,time_mpltPath,label='mpltPath')
plt.plot(n_points,time_ray_tracing_numpy_numba,label='ray_tracing_numpy_numba')
plt.plot(n_points,time_is_inside_sm_parallel,label='is_inside_sm_parallel')
plt.plot(n_points,time_is_inside_postgis_parallel,label='is_inside_postgis_parallel')
plt.xlabel("N points")
plt.ylabel("time (sec)")
plt.legend(loc = 'best')
plt.show()

CONCLUSION

The fastest algorithms are:

1- is_inside_sm_parallel

2- is_inside_postgis_parallel

3- parallelpointinpolygon (@epifanio)

Print page numbers on pages when printing html

Can you try this, you can use content: counter(page);

     @page {
       @bottom-left {
            content: counter(page) "/" counter(pages);
        }
     }

Ref: http://www.w3.org/TR/CSS21/generate.html#counters

http://www.princexml.com/doc/9.0/page-numbers/

How to set the font style to bold, italic and underlined in an Android TextView?

This should make your TextView bold, underlined and italic at the same time.

strings.xml

<resources>
    <string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>

To set this String to your TextView, do this in your main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/register" />

or In JAVA,

TextView textView = new TextView(this);
textView.setText(R.string.register);

Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.

String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);

OUTPUT

enter image description here

How can I concatenate a string within a loop in JSTL/JSP?

Perhaps this will work?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${stat.first ? '' : myVar} ${currentItem}" />
</c:forEach>

I have filtered my Excel data and now I want to number the rows. How do I do that?

Try this function:

=SUBTOTAL(3, B$2:B2)

You can find more details in this blog entry.

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

Print in one line dynamically

In Python 3 you can do it this way:

for item in range(1,10):
    print(item, end =" ")

Outputs:

1 2 3 4 5 6 7 8 9 

Tuple: You can do the same thing with a tuple:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

Outputs:

1 - 2 - 3 - 4 - 5 - 

Another example:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

Outputs:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

You can even unpack your tuple like this:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

Outputs:

1 2
A B
3 4
Cat Dog

another variation:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

Outputs:

1
2


A
B


3
4


Cat
Dog

Dynamic function name in javascript?

For setting the name of an existing anonymous function:
(Based on @Marcosc's answer)

var anonymous = function() { return true; }

var name = 'someName';
var strFn = anonymous.toString().replace('function ', 'return function ' + name);
var fn = new Function(strFn)();

console.log(fn()); // —> true

Demo.

Note: Don't do it ;/

Create, read, and erase cookies with jQuery

Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.

Uncaught TypeError: Cannot read property 'top' of undefined

I ran through similar problem and found that I was trying to get the offset of footer but I was loading my script inside a div before the footer. It was something like this:

<div> I have some contents </div>
<script>
  $('footer').offset().top;
</script>
<footer>This is footer</footer>

So, the problem was, I was calling the footer element before the footer was loaded.

I pushed down my script below footer and it worked fine!

Unit testing with Spring Security

Just do it the usual way and then insert it using SecurityContextHolder.setContext() in your test class, for example:

Controller:

Authentication a = SecurityContextHolder.getContext().getAuthentication();

Test:

Authentication authentication = Mockito.mock(Authentication.class);
// Mockito.whens() for your authorization object
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

try this

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

hello = tf.constant('Hello, TensorFlow!')

sess = tf.compat.v1.Session()

print(sess.run(hello))

How do I make a relative reference to another workbook in Excel?

easier & shorter via indirect: INDIRECT("'..\..\..\..\Supply\SU\SU.ods'#$Data.$A$2:$AC$200")

however indirect() has performance drawbacks if lot of links in workbook

I miss construct like: ['../Data.ods']#Sheet1.A1 in LibreOffice. The intention is here: if I create a bunch of master workbooks and depending report workbooks in limited subtree of directories in source file system, I can zip whole directory subtree with complete package of workbooks and send it to other cooperating person per Email or so. It will be saved in some other absolute pazth on target system, but linkage works again in new absolute path because it was coded relatively to subtree root.

Interesting 'takes exactly 1 argument (2 given)' Python error

The call

e.extractAll("th")

for a regular method extractAll() is indeed equivalent to

Extractor.extractAll(e, "th")

These two calls are treated the same in all regards, including the error messages you get.

If you don't need to pass the instance to a method, you can use a staticmethod:

@staticmethod
def extractAll(tag):
    ...

which can be called as e.extractAll("th"). But I wonder why this is a method on a class at all if you don't need to access any instance.

High CPU Utilization in java application - why?

In the thread dump you can find the Line Number as below.

for the main thread which is currently running...

"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
   java.lang.Thread.State: **RUNNABLE**
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:313)
    at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**

How to show full column content in a Spark Dataframe?

Within Databricks you can visualize the dataframe in a tabular format. With the command:

display(results)

It will look like

enter image description here

Shortcut to open file in Vim

:find is another option.

I open vim from the root of my project and have the path set to there.

Then, I can open files located anywhere in the tree using:

:find **/filena< tab >

Tab will autocomplete through various matches. (** tells it to search recursively through the path).

Import CSV file as a pandas DataFrame

%cd C:\Users\asus\Desktop\python
import pandas as pd
df = pd.read_csv('value.txt')
df.head()
    Date    price   factor_1    factor_2
0   2012-06-11  1600.20 1.255   1.548
1   2012-06-12  1610.02 1.258   1.554
2   2012-06-13  1618.07 1.249   1.552
3   2012-06-14  1624.40 1.253   1.556
4   2012-06-15  1626.15 1.258   1.552

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

We have a package to do the very job:

sudo apt-get install randomize-lines

Example:

Create an ordered list of numbers, and save it to 1000.txt:

seq 1000 > 1000.txt

to shuffle it, simply use

rl 1000.txt

How to remove unwanted space between rows and columns in table?

Try this,

table{
border-collapse: collapse; /* 'cellspacing' equivalent */
}

table td, 
table th{
padding: 0; /* 'cellpadding' equivalent */
}

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

There are many solutions to this problem but for my situation, I just needed to correct the DATE on the machine/server (Ubuntu 16.04 Server).

i) Check the date of your server and correct it.

ii) Run sudo /etc/init.d/mysql restart

That should get it started.

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

Rails: FATAL - Peer authentication failed for user (PG::Error)

This is the most foolproof way to get your rails app working with postgres in the development environment in Ubuntu 13.10.

1) Create rails app with postgres YAML and 'pg' gem in the Gemfile:

$ rails new my_application -d postgresql

2) Give it some CRUD functionality. If you're just seeing if postgres works, create a scaffold:

$ rails g scaffold cats name:string age:integer colour:string

3) As of rails 4.0.1 the -d postgresql option generates a YAML that doesn't include a host parameter. I found I needed this. Edit the development section and create the following parameters:

encoding: UTF-8
host: localhost
database: my_application_development
username: thisismynewusername
password: thisismynewpassword 

Note the database parameter is for a database that doesn't exit yet, and the username and password are credentials for a role that doesn't exist either. We'll create those later on!

This is how config/database.yml should look (no shame in copypasting :D ):

development:
  adapter: postgresql
  pool: 5
  # these are our new parameters
  encoding: UTF-8
  database: my_application_development
  host: localhost
  username: thisismynewusername
  password: thisismynewpassword

test:
  # this won't work 
  adapter: postgresql
  encoding: unicode
  database: my_application_test
  pool: 5
  username: my_application
  password:

production:
  # this won't work 
  adapter: postgresql
  encoding: unicode
  database: my_application_production
  pool: 5
  username: my_application
  password:

4) Start the postgres shell with this command:

$ psql

4a) You may get this error if your current user (as in your computer user) doesn't have a corresponding administration postgres role.

psql: FATAL:  role "your_username" does not exist

Now I've only installed postgres once, so I may be wrong here, but I think postgres automatically creates an administration role with the same credentials as the user you installed postgres as.

4b) So this means you need to change to the user that installed postgres to use the psql command and start the shell:

$ sudo su postgres

And then run

$ psql

5) You'll know you're in the postgres shell because your terminal will look like this:

$ psql
psql (9.1.10)
Type "help" for help.

postgres=# 

6) Using the postgresql syntax, let's create the user we specified in config/database.yml's development section:

postgres=# CREATE ROLE thisismynewusername WITH LOGIN PASSWORD 'thisismynewpassword';

Now, there's some subtleties here so let's go over them.

  • The role's username, thisismynewusername, does not have quotes of any kind around it
  • Specify the keyword LOGIN after the WITH. If you don't, the role will still be created, but it won't be able to log in to the database!
  • The role's password, thisismynewpassword, needs to be in single quotes. Not double quotes.
  • Add a semi colon on the end ;)

You should see this in your terminal:

postgres=#
CREATE ROLE
postgres=#

That means, "ROLE CREATED", but postgres' alerts seem to adopt the same imperative conventions of git hub.

7) Now, still in the postgres shell, we need to create the database with the name we set in the YAML. Make the user we created in step 6 its owner:

postgres=# CREATE DATABASE my_application_development OWNER thisismynewusername;

You'll know if you were successful because you'll get the output:

CREATE DATABASE

8) Quit the postgres shell:

\q

9) Now the moment of truth:

$ RAILS_ENV=development rake db:migrate

If you get this:

==  CreateCats: migrating =================================================
-- create_table(:cats)
   -> 0.0028s
==  CreateCats: migrated (0.0028s) ========================================

Congratulations, postgres is working perfectly with your app.

9a) On my local machine, I kept getting a permission error. I can't remember it exactly, but it was an error along the lines of

Can't access the files. Change permissions to 666.

Though I'd advise thinking very carefully about recursively setting write privaledges on a production machine, locally, I gave my whole app read write privileges like this:

9b) Climb up one directory level:

$ cd ..

9c) Set the permissions of the my_application directory and all its contents to 666:

$ chmod -R 0666 my_application

9d) And run the migration again:

$ RAILS_ENV=development rake db:migrate

==  CreateCats: migrating =================================================
-- create_table(:cats)
   -> 0.0028s
==  CreateCats: migrated (0.0028s) ========================================

Some tips and tricks if you muck up

Try these before restarting all of these steps:

The mynewusername user doesn't have privileges to CRUD to the my_app_development database? Drop the database and create it again with mynewusername as the owner:

1) Start the postgres shell:

$ psql

2) Drop the my_app_development database. Be careful! Drop means utterly delete!

postgres=# DROP DATABASE my_app_development;

3) Recreate another my_app_development and make mynewusername the owner:

postgres=# CREATE DATABASE my_application_development OWNER mynewusername;

4) Quit the shell:

postgres=# \q

The mynewusername user can't log into the database? Think you wrote the wrong password in the YAML and can't quite remember the password you entered using the postgres shell? Simply alter the role with the YAML password:

1) Open up your YAML, and copy the password to your clipboard:

 development:
      adapter: postgresql
      pool: 5
      # these are our new parameters
      encoding: UTF-8
      database: my_application_development
      host: localhost
      username: thisismynewusername
      password: musthavebeenverydrunkwheniwrotethis

2) Start the postgres shell:

$ psql    

3) Update mynewusername's password. Paste in the password, and remember to put single quotes around it:

postgres=# ALTER ROLE mynewusername PASSWORD `musthavebeenverydrunkwheniwrotethis`;

4) Quit the shell:

postgres=# \q

Trying to connect to localhost via a database viewer such as Dbeaver, and don't know what your postgres user's password is? Change it like this:

1) Run passwd as a superuser:

$ sudo passwd postgres

2) Enter your accounts password for sudo (nothing to do with postgres):

[sudo] password for starkers: myaccountpassword

3) Create the postgres account's new passwod:

Enter new UNIX password: databasesarefun
Retype new UNIX password: databasesarefun
passwd: password updated successfully

Getting this error message?:

Run `$ bin/rake db:create db:migrate` to create your database
$ rake db:create db:migrate
PG::InsufficientPrivilege: ERROR:  permission denied to create database

4) You need to give your user the ability to create databases. From the psql shell:

ALTER ROLE thisismynewusername WITH CREATEDB

What does bundle exec rake mean?

When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.

To enforce the desired gem version you take the help of bundle exec command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.

I have also written a post about it which also shows how we can avoid using it using bin stubs.

Get the key corresponding to the minimum value within a dictionary

Here's an answer that actually gives the solution the OP asked for:

>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1]) 
(321, 0)

Using d.iteritems() will be more efficient for larger dictionaries, however.

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.

Remember to update your password if you've got the option selected 'Run whether user is logged on or not'

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Rewriting:

There are radical differences between mobile and desktop environment, as well as between the way in which applications were developed to a handful of years ago and today:

a) mobile devices need to conserve energy. Part of the value they offer. So you need to save resources. Threads are an expensive resource. Halt the progress of a thread is an unacceptable waste of this resource.

b) Nowadays the user is much more demanding. To assist them, we believe that it deserves to have full working CPU and the smallest possible expenditure of energy. Its application is not alone on the device, there is an unknow number of another apps running at same time and your app is not necessarily the most urgent.

c) system-level locks are not an option: a mobile device works with a number of events and services in the background and it is not right for any of them can be locked by an application.

Think about the user receiving a phone call while your "system lock" is working...

Based on the above facts, the answer to the proposed question are:

  • There is a viable way to build a dialog that blocks the main thread until a response from the user?

No. Workarounds do user experience get worse and it may make the mistake of blaming the system itself. This is unfair and penalizes the platform and all its developers.

  • Is there a way to block the entire system with a dialogue?

No. This is strictly forbidden on the platform. No application can interfere with the operation of the system or other applications.

  • I need to refactor my application, or rethink my way of programming to suit me on the Android mobile system architecture.

Yes. Including this aspect.

Dynamically creating keys in a JavaScript associative array

The original code (I added the line numbers so can refer to them):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // Prints nothing.

Almost there...

  • line 1: you should do a trim on text so it is name = oscar.

  • line 3: okay as long as you always have spaces around your equal. It might be better to not trim in line 1. Use = and trim each keyValuePair

  • add a line after 3 and before 4:

      key = keyValuePair[0];`
    
  • line 4: Now becomes:

      dict[key] = keyValuePair[1];
    
  • line 5: Change to:

      alert( dict['name'] );  // It will print out 'oscar'
    

I'm trying to say that the dict[keyValuePair[0]] does not work. You need to set a string to keyValuePair[0] and use that as the associative key. That is the only way I got mine to work. After you have set it up, you can either refer to it with numeric index or key in quotes.

jQuery won't parse my JSON from AJAX query

Is your server sending data as Content-Type "*/json"? If not, modify the response headers accordingly. Sending "application/json" would be fine, for example.

This compilation unit is not on the build path of a Java project

If it is a Maven project then sometimes re-importing of it helps:

  1. Right-click the project in the Project Explorer and choose Delete.
  2. File > Import... > Maven > Existing Maven Projects > Next > Root Directory > Browse your project from Disk.

Hope it will resolve the issue.