Programs & Examples On #Gets

Anything related to C or C++ standard library functions gets (C) or std::gets (C++). These functions are used to read a sequence of characters from an input stream and to write it into a character buffer as a string. DO NOT USE THESE FUNCTIONS: they are deprecated, and since C11 gets is no longer part of the standard.

Why is the gets function so dangerous that it should not be used?

You should not use gets since it has no way to stop a buffer overflow. If the user types in more data than can fit in your buffer, you will most likely end up with corruption or worse.

In fact, ISO have actually taken the step of removing gets from the C standard (as of C11, though it was deprecated in C99) which, given how highly they rate backward compatibility, should be an indication of how bad that function was.

The correct thing to do is to use the fgets function with the stdin file handle since you can limit the characters read from the user.

But this also has its problems such as:

  • extra characters entered by the user will be picked up the next time around.
  • there's no quick notification that the user entered too much data.

To that end, almost every C coder at some point in their career will write a more useful wrapper around fgets as well. Here's mine:

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

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

with some test code:

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        printf ("No input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long\n");
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

It provides the same protections as fgets in that it prevents buffer overflows but it also notifies the caller as to what happened and clears out the excess characters so that they do not affect your next input operation.

Feel free to use it as you wish, I hereby release it under the "do what you damn well want to" licence :-)

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

in mvc 5

              @Html.EditorFor(x => x.Address, 
              new {htmlAttributes = new {@class = "form-control", 
                   @placeholder = "Complete Address", @cols = 10, @rows = 10 } })

Does Spring Data JPA have any way to count entites using method name resolving?

If anyone wants to get the count with based on multiple conditions than here is a sample custom query

@Query("select count(sl) from SlUrl sl where sl.user =?1 And sl.creationDate between ?2 And ?3")
    long countUrlsBetweenDates(User user, Date date1, Date date2);

Apply multiple functions to multiple groupby columns

For the first part you can pass a dict of column names for keys and a list of functions for the values:

In [28]: df
Out[28]:
          A         B         C         D         E  GRP
0  0.395670  0.219560  0.600644  0.613445  0.242893    0
1  0.323911  0.464584  0.107215  0.204072  0.927325    0
2  0.321358  0.076037  0.166946  0.439661  0.914612    1
3  0.133466  0.447946  0.014815  0.130781  0.268290    1

In [26]: f = {'A':['sum','mean'], 'B':['prod']}

In [27]: df.groupby('GRP').agg(f)
Out[27]:
            A                   B
          sum      mean      prod
GRP
0    0.719580  0.359790  0.102004
1    0.454824  0.227412  0.034060

UPDATE 1:

Because the aggregate function works on Series, references to the other column names are lost. To get around this, you can reference the full dataframe and index it using the group indices within the lambda function.

Here's a hacky workaround:

In [67]: f = {'A':['sum','mean'], 'B':['prod'], 'D': lambda g: df.loc[g.index].E.sum()}

In [69]: df.groupby('GRP').agg(f)
Out[69]:
            A                   B         D
          sum      mean      prod  <lambda>
GRP
0    0.719580  0.359790  0.102004  1.170219
1    0.454824  0.227412  0.034060  1.182901

Here, the resultant 'D' column is made up of the summed 'E' values.

UPDATE 2:

Here's a method that I think will do everything you ask. First make a custom lambda function. Below, g references the group. When aggregating, g will be a Series. Passing g.index to df.ix[] selects the current group from df. I then test if column C is less than 0.5. The returned boolean series is passed to g[] which selects only those rows meeting the criteria.

In [95]: cust = lambda g: g[df.loc[g.index]['C'] < 0.5].sum()

In [96]: f = {'A':['sum','mean'], 'B':['prod'], 'D': {'my name': cust}}

In [97]: df.groupby('GRP').agg(f)
Out[97]:
            A                   B         D
          sum      mean      prod   my name
GRP
0    0.719580  0.359790  0.102004  0.204072
1    0.454824  0.227412  0.034060  0.570441

How to get records randomly from the oracle database?

Here's how to pick a random sample out of each group:

SELECT GROUPING_COLUMN, 
       MIN (COLUMN_NAME) KEEP (DENSE_RANK FIRST ORDER BY DBMS_RANDOM.VALUE) 
         AS RANDOM_SAMPLE
FROM TABLE_NAME
GROUP BY GROUPING_COLUMN
ORDER BY GROUPING_COLUMN;

I'm not sure how efficient it is, but if you have a lot of categories and sub-categories, this seems to do the job nicely.

Calling a PHP function from an HTML form in the same file

in case you don't want to use Ajax , and want your page to reload .

<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}    
?>

Comments in Markdown

This works on GitHub:

[](Comment text goes here)

The resulting HTML looks like:

<a href="Comment%20text%20goes%20here"></a>

Which is basically an empty link. Obviously you can read that in the source of the rendered text, but you can do that on GitHub anyway.

Scanner is never closed

According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

What are the benefits to marking a field as `readonly` in C#?

readonly can be initialized at declaration or get its value from the constructor only. Unlike const it has to be initialized and declare at the same time. readonly has everything const has, plus constructor initialization

code https://repl.it/HvRU/1

using System;

class MainClass {
    public static void Main (string[] args) {

        Console.WriteLine(new Test().c);
        Console.WriteLine(new Test("Constructor").c);
        Console.WriteLine(new Test().ChangeC()); //Error A readonly field 
        // `MainClass.Test.c' cannot be assigned to (except in a constructor or a 
        // variable initializer)
    }


    public class Test {
        public readonly string c = "Hello World";
        public Test() {

        }

        public Test(string val) {
          c = val;
        }

        public string ChangeC() {
            c = "Method";
            return c ;
        }
    }
}

What is an idempotent operation?

In short, Idempotent operations means that the operation will not result in different results no matter how many times you operate the idempotent operations.

For example, according to the definition of the spec of HTTP, GET, HEAD, PUT, and DELETE are idempotent operations; however POST and PATCH are not. That's why sometimes POST is replaced by PUT.

What is the difference between a schema and a table and a database?

In a nutshell, a schema is the definition for the entire database, so it includes tables, views, stored procedures, indexes, primary and foreign keys, etc.

Converting <br /> into a new line for use in a text area

The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.

echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");

function function_one() {
    preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}

function function_two() {
    str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}

function benchmark() {
    $count = 10000000;
    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_one();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function one\n";



    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_two();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();

Results:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

Where can I download mysql jdbc jar from?

If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar

Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip

powershell - list local users and their groups

Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.

PowerShell - List local user accounts

Fast way

Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'" | select name, fullname

Slow way

Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

Writing html form data to a txt file without the use of a webserver

Something like this?

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">Please type in this box. When you 

click the Download button, the contents of this box will be downloaded to 

your machine at the location you specify. Pretty nifty. </textarea>
  <input type="submit" value="Download">
</form>
</body>
</html>

The transaction log for the database is full

Try this:

If possible restart the services MSSQLSERVER and SQLSERVERAGENT.

Converting Integers to Roman Numerals - Java

Alternative solution based on the OP's own solution by utilizing an enum. Additionally, a parser and round-trip tests are included.

public class RomanNumber {
    public enum Digit {
        M(1000, 3),
        CM(900, 1),
        D(500, 1),
        CD(400, 1),
        C(100, 3),
        XC(90, 1),
        L(50, 1),
        XL(40, 1),
        X(10, 3),
        IX(9, 1),
        V(5, 1),
        IV(4, 1),
        I(1, 3);

        public final int value;
        public final String symbol = name();
        public final int maxArity;

        private Digit(int value, int maxArity) {
            this.value = value;
            this.maxArity = maxArity;
        }
    }

    private static final Digit[] DIGITS = Digit.values();

    public static String of(int number) {
        if (number < 1 || 3999 < number) {
            throw new IllegalArgumentException(String.format(
                    "Roman numbers are only defined for numbers between 1 and 3999 (%d was given)",
                    number
            ));
        }

        StringBuilder sb = new StringBuilder();
        for (Digit digit : DIGITS) {
            int value = digit.value;
            String symbol = digit.symbol;

            while (number >= value) {
                sb.append(symbol);
                number -= value;
            }
        }

        return sb.toString();
    }

    public static int parse(String roman) {
        if (roman.isEmpty()) {
            throw new NumberFormatException("The empty string does not comprise a valid Roman number");
        }

        int number = 0;
        int offset = 0;
        for (Digit digit : DIGITS) {
            int value = digit.value;
            int maxArity = digit.maxArity;
            String symbol = digit.symbol;

            for (int i = 0; i < maxArity && roman.startsWith(symbol, offset); i++) {
                number += value;
                offset += symbol.length();
            }
        }
        if (offset != roman.length()) {
            throw new NumberFormatException(String.format(
                    "The string '%s' does not comprise a valid Roman number",
                    roman
            ));
        }
        return number;
    }

    /** TESTS */
    public static void main(String[] args) {

        /* Demonstrating round-trip for all possible inputs. */

        for (int number = 1; number <= 3999; number++) {
            String roman = of(number);
            int parsed = parse(roman);
            if (parsed != number) {
                System.err.format(
                        "ERROR: number: %d, roman: %s, parsed: %d\n",
                        number,
                        roman,
                        parsed
                );
            }
        }

        /* Some illegal inputs. */

        int[] illegalNumbers = { -1, 0, 4000, 4001 };
        for (int illegalNumber : illegalNumbers) {
            try {
                of(illegalNumber);
                System.err.format(
                        "ERROR: Expected failure on number %d\n",
                        illegalNumber
                );
            } catch (IllegalArgumentException e) {
                // Failed as expected.
            }
        }

        String[] illegalRomans = { "MMMM", "CDCD", "IM", "T", "", "VV", "DM" };
        for (String illegalRoman : illegalRomans) {
            try {
                parse(illegalRoman);
                System.err.format(
                        "ERROR: Expected failure on roman %s\n",
                        illegalRoman
                );
            } catch (NumberFormatException e) {
                // Failed as expected.
            }
        }
    }
}

jQuery get text as number

var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
     // do something
}

Generate an integer sequence in MySQL

Counter from 1 to 1000:

  • no need to create a table
  • time to execute ~ 0.0014 sec
  • can be converted into a view
    select tt.row from
    (
    SELECT cast( concat(t.0,t2.0,t3.0) + 1 As UNSIGNED) as 'row' FROM 
    (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t,
    (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2, 
    (select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3
    ) tt
    order by tt.row

Credits: answer, comment by Seth McCauley below the answer.

converting CSV/XLS to JSON?

I just found this:

http://tamlyn.org/tools/csv2json/

( Note: you have to have your csv file available via a web address )

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

internal/modules/cjs/loader.js:582 throw err

it finally worked for me after I did sudo npm i cjs-loader (and make sure to install express, not just express-http-proxy)

Global variables in Javascript across multiple files

Hi to pass values from one js file to another js file we can use Local storage concept

<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>

Two.js file

function myFunction() {
var test =localStorage.name;

 alert(test);
}

Three.js File

localStorage.name = 1;

How to iterate over the keys and values with ng-repeat in AngularJS?

we can follow below procedure to avoid display of key-values in alphabetical order.

Javascript

$scope.data = {
   "id": 2,
   "project": "wewe2012",
   "date": "2013-02-26",
   "description": "ewew",
   "eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
    var test = {};
    test[key]=$scope.data[key];
    array.push(test);
}
$scope.data = array;

HTML

<p ng-repeat="obj in data">
   <font ng-repeat="(key, value) in obj">
      {{key}} : {{value}}
   </font>
</p>

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

In Bootstrap open Enlarge image in modal

So I have put together a very rough modal in jsfiddle for you to take hints from.

JSFiddle

$("#pop").on("click", function(e) {
  // e.preventDefault() this is stopping the redirect to the image its self
  e.preventDefault();
  // #the-modal is the img tag that I use as the modal.
  $('#the-modal').modal('toggle');
});

The part that you are missing is the hidden modal that you want to display when the link is clicked. In the example I used a second image as the modal and added the Bootstap classes.

Multiple aggregate functions in HAVING clause

Here I am writing full query which will clear your all doubts

SELECT BillingDate,
       COUNT(*) AS BillingQty,
       SUM(BillingTotal) AS BillingSum
FROM Billings
WHERE BillingDate BETWEEN '2002-05-01' AND '2002-05-31'
GROUP BY BillingDate
HAVING COUNT(*) > 1
AND SUM(BillingTotal) > 100
ORDER BY BillingDate DESC

How to Execute a Python File in Notepad ++?

All the answers for the Run->Run menu option go with the "/K" switch of cmd, so the terminal stays open, or "-i" for python.exe so python forces interactive mode - both to preserve the output for you to observe.

Yet in cmd /k you have to type exit to close it, in the python -i - quit(). If that is too much typing for your liking (for me it sure is :), the Run command to use is

cmd /k C:\Python27\python.exe  "$(FULL_CURRENT_PATH)" & pause & exit

C:\Python27\python.exe - obviously the full path to your python install (or just python if you want to go with the first executable in your user's path).

& is unconditional execution of the next command in Windows - unconditional as it runs regardless of the RC of the previous command (&& is "and" - run only if the previous completed successfully, || - is "or").

pause - prints "Press any key to continue . . ." and waits for any key (that output can be suppressed if need).

exit - well, types the exit for you :)

So at the end, cmd runs python.exe which executes the current file and keeps the window opened, pause waits for you to press any key, and exit finally close the window once you press that any key.

What is wrong with my SQL here? #1089 - Incorrect prefix key

When you give id as a primary key then a pop up is come and those aske you to how many size of this primary key. So you just leave blank because by default int value is set 11. Click then ok on those pop up without any enter a number. in this type of error never will you face in future. Thank you

Best radio-button implementation for IOS

Try DLRadioButton, works for both Swift and ObjC. You can also use images to indicate selection status or customize your own style.

Check it out at GitHub.

radio button for iOS

**Update: added the option for putting selection indicator on the right side.

**Update: added square button, IBDesignable, improved performance.

**Update: added multiple selection support.

Which are more performant, CTE or temporary tables?

CTE has its uses - when data in the CTE is small and there is strong readability improvement as with the case in recursive tables. However, its performance is certainly no better than table variables and when one is dealing with very large tables, temporary tables significantly outperform CTE. This is because you cannot define indices on a CTE and when you have large amount of data that requires joining with another table (CTE is simply like a macro). If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables.

How could I create a function with a completion handler in Swift?

I'm a little confused about custom made completion handlers. In your example:

Say you have a download function to download a file from network,and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

Your // download code will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true and completion Handler(success: flag) without waiting for your download code to be finished?

Django: Model Form "object has no attribute 'cleaned_data'"

I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.

Left padding a String with Zeros

Here's another approach:

int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)

How to get the second column from command output?

Use -F [field separator] to split the lines on "s:

awk -F '"' '{print $2}' your_input_file

or for input from pipe

<some_command> | awk -F '"' '{print $2}'

output:

A B
C
D

Can't install laravel installer via composer

For Ubuntu 16.04, I have used this command for PHP7.2 and it worked for me.

sudo apt-get install php7.2-zip

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

[HttpPost]
public ActionResult TV(MyModel id)
{
    return Json(new { success = true });
}

dispatch_after - GCD in Swift?

Apple has a dispatch_after snippet for Objective-C:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    <#code to be executed after a specified delay#>
});

Here is the same snippet ported to Swift 3:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + <#delayInSeconds#>) {
  <#code to be executed after a specified delay#>
}

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

I got the same error because of a simple typo in vhost.conf. Remember to make sure you don't have any errors in the config files.

apachectl configtest

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

How to convert a full date to a short date in javascript?

Here you go:

(new Date()).toLocaleDateString('en-US');

That's it !!

you can use it on any date object

let's say.. you have an object called "currentDate"

var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy

(or)

If you want it in local format then

currentDate.toLocaleDateString(); // gives date in local Format

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

How to round the double value to 2 decimal points?

There's no difference in internal representation between 2 and 2.00. You can use Math.round to round a value to the nearest integer - to make that round to 2 decimal places you could multiply by 100, round, and then divide by 100, but you shouldn't expect the result to be exactly 2dps, due to the nature of binary floating point arithmetic.

If you're only interested in formatting a value to two decimal places, look at DecimalFormat - if you're interested in a number of decimal places while calculating you should really be using BigDecimal. That way you'll know that you really are dealing with decimal digits, rather than "the nearest available double value".

Another option you may want to consider if you're always dealing with two decimal places is to store the value as a long or BigInteger, knowing that it's exactly 100 times the "real" value - effectively storing cents instead of dollars, for example.

What to do on TransactionTooLargeException

sometime Activity include some Fragment when Activityneed to totally recreate Fragments content, if the sportFragmentManager.fragments without clear history fragments

    val fragments = sportFragmentManager.fragments
    val transaction = sportFragmentManager.beginTransaction()
    for (frag in fragments){
        transaction.remove(frag)
    }
    transaction.commitAllowingStateLoss()

serveral times recreate Fragments the Activity will happen (debug use tooLargeTool)

 W/ActivityStopInfo: Bundle stats:
 W/ActivityStopInfo:   android:viewHierarchyState [size=2304]
 W/ActivityStopInfo:     android:views [size=2256]
 W/ActivityStopInfo:   android:support:fragments [size=519072]
 W/ActivityStopInfo: PersistableBundle stats:
 W/ActivityStopInfo:   [null]

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

How do I look inside a Python object?

First, read the source.

Second, use the dir() function.

How do I add space between two variables after a print in Python

print str(count) + ' ' + str(conv) - This did not work. However, replacing + with , works for me

How to find an available port?

If you don't mind the port used, specify a port of 0 to the ServerSocket constructor and it will listen on any free port.

ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort());

If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:

public ServerSocket create(int[] ports) throws IOException {
    for (int port : ports) {
        try {
            return new ServerSocket(port);
        } catch (IOException ex) {
            continue; // try next port
        }
    }

    // if the program gets here, no port in the range was found
    throw new IOException("no free port found");
}

Could be used like so:

try {
    ServerSocket s = create(new int[] { 3843, 4584, 4843 });
    System.out.println("listening on port: " + s.getLocalPort());
} catch (IOException ex) {
    System.err.println("no available ports");
}

Shell script to check if file exists

You can do it in one line:

ls /home/edward/bank1/fiche/Test* >/dev/null 2>&1 && echo "found one" || echo "found none"

To understand what it does you have to decompose the command and have a basic awareness of boolean logic.

Directly from bash man page:

[...]
expression1 && expression2
     True if both expression1 and expression2 are true.
expression1 || expression2
     True if either expression1 or expression2 is true.
[...]

In the shell (and in general in unix world), the boolean true is a program that exits with status 0.

ls tries to list the pattern, if it succeed (meaning the pattern exists) it exits with status 0, 2 otherwise (have a look at ls man page for details).

In our case there are actually 3 expressions, for the sake of clarity I will put parenthesis, although they are not needed because && has precedence on ||:

 (expression1 && expression2) || expression3

so if expression1 is true (ie: ls found the pattern) it evaluates expression2 (which is just an echo and will exit with status 0). In this case expression3 is never evaluate because what's on the left site of || is already true and it would be a waste of resources trying to evaluate what's on the right.

Otherwise, if expression1 is false, expression2 is not evaluated but in this case expression3 is.

Clear text input on click with AngularJS

$scope.clearSearch = function () {
    $scope.searchAll = "";
};

http://jsfiddle.net/nzPJD/

JsFiddle of how you could do it without using inline JS.

How do I use floating-point division in bash?

Use calc. It's the easiest I found example:

calc 1+1

 2

calc 1/10

 0.1

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to grep and replace

Other solutions mix regex syntaxes. To use perl/PCRE patterns for both search and replace, and only process matching files, this works quite well:

grep -rlIZPi 'match1' | xargs -0r perl -pi -e 's/match2/replace/gi;'

match1 and match2 are usually identical but match1 can be simplified to remove more advanced features that are only relevant to the substitution, e.g. capturing groups.

Translation: grep recursively and list matching filenames, each separated by nul to protect any special characters; pipe any filenames to xargs which is expecting a nul-separated list; if any filenames are received, pass them to perl to perform the actual substitutions.

For case-sensitive matching, drop the i flag from grep and the i pattern modifier from the s/// expression, but not the i flag from perl itself. Remove the I flag from grep to include binary files.

File opens instead of downloading in internet explorer in a href link

This must be a matter of http headers.

see here: HTTP Headers for File Downloads

The server should tell your browser to download the file by sending

Content-Type: application/octet-stream; 
Content-Disposition: attachment;

in the headers

jQuery.animate() with css class only, without explicit styles

In many cases you're better off using CSS transitions for this, and in old browsers the easing will simply be instant. Most animations (like fade in/out) are very trivial to implement and the browser does all the legwork for you. https://developer.mozilla.org/en/docs/Web/CSS/transition

VBA paste range

To literally fix your example you would use this:

Sub Normalize()


    Dim Ticker As Range
    Sheets("Sheet1").Activate
    Set Ticker = Range(Cells(2, 1), Cells(65, 1))
    Ticker.Copy

    Sheets("Sheet2").Select
    Cells(1, 1).PasteSpecial xlPasteAll



End Sub

To Make slight improvments on it would be to get rid of the Select and Activates:

Sub Normalize()
    With Sheets("Sheet1")
        .Range(.Cells(2, 1), .Cells(65, 1)).Copy Sheets("Sheet2").Cells(1, 1)
    End With
End Sub

but using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.

Sub Normalize()
Dim CopyFrom As Range

Set CopyFrom = Sheets("Sheet1").Range("A2", [A65])
Sheets("Sheet2").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value

End Sub

To define the CopyFrom you can use anything you want to define the range, You could use Range("A2:A65"), Range("A2",[A65]), Range("A2", "A65") all would be valid entries. also if the A2:A65 Will never change the code could be further simplified to:

Sub Normalize()

Sheets("Sheet2").Range("A1:A65").Value = Sheets("Sheet1").Range("A2:A66").Value

End Sub

I added the Copy from range, and the Resize property to make it slightly more dynamic in case you had other ranges you wanted to use in the future.

How to update/modify an XML file in python?

For the modification, you could use tag.text from xml. Here is snippet:

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()

for rank in root.iter('rank'):
    new_rank = int(rank.text) + 1
    rank.text = str(new_rank)
    
tree.write('output.xml')

The rank in the code is example of tag, which depending on your XML file contents.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

when bullet have to hide then use:

li { list-style: none;}

when bullet have to list show, then use:

li { list-style: initial;}

Convert Float to Int in Swift

Explicit Conversion

Converting to Int will lose any precision (effectively rounding down). By accessing the math libraries you can perform explicit conversions. For example:

If you wanted to round down and convert to integer:

let f = 10.51
let y = Int(floor(f))

result is 10.

If you wanted to round up and convert to integer:

let f = 10.51
let y = Int(ceil(f))

result is 11.

If you want to explicitly round to the nearest integer

let f = 10.51
let y = Int(round(f))

result is 11.

In the latter case, this might seem pedantic, but it's semantically clearer as there is no implicit conversion...important if you're doing signal processing for example.

How do I fire an event when a iframe has finished loading in jQuery?

I'm pretty certain that it cannot be done.

Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)

Too bad.

How to get temporary folder for current user

DO NOT use this:

System.Environment.GetEnvironmentVariable("TEMP")

Environment variables can be overridden, so the TEMP variable is not necessarily the directory.

The correct way is to use System.IO.Path.GetTempPath() as in the accepted answer.

Swift add icon/image in UITextField

Swift 5

@IBOutlet weak var paswd: UITextField! {
    didSet{
      paswd.setLeftView(image: UIImage.init(named: "password")!)
      paswd.tintColor = .darkGray
      paswd.isSecureTextEntry = true
    }   
 }

I have created extension

extension UITextField {
  func setLeftView(image: UIImage) {
    let iconView = UIImageView(frame: CGRect(x: 10, y: 10, width: 25, height: 25)) // set your Own size
    iconView.image = image
    let iconContainerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 35, height: 45))
    iconContainerView.addSubview(iconView)
    leftView = iconContainerView
    leftViewMode = .always
    self.tintColor = .lightGray
  }
}

Result

enter image description here

Select second last element with css

In CSS3 you have:

:nth-last-child(2)

See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

nth-last-child Browser Support:

  • Chrome 2
  • Firefox 3.5
  • Opera 9.5, 10
  • Safari 3.1, 4
  • Internet Explorer 9

How do I join two lines in vi?

Press Shift + 4 ("$") on the first line, then Shift + j ("J").

And if you want help, go into vi, and then press F1.

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

How does data binding work in AngularJS?

AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.

$watch() :-

This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

$digest() -

This function iterates through all the watches in the $scope object, and its child $scope objects
(if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

$apply() -

Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

How to copy a selection to the OS X clipboard

I used:

map <C-x> :!pbcopy<CR>
vmap <C-c> :w !pbcopy<CR><CR>

It worked really well.

RegEx - Match Numbers of Variable Length

Try this:

{[0-9]{1,3}:[0-9]{1,3}}

The {1,3} means "match between 1 and 3 of the preceding characters".

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

You can't. Your only option is to divide this into multiple tables and put the form tag outside of it. You could end up nesting your tables, but this is not recommended:

<table>
  <tr><td><form>
    <table><tr><td>id</td><td>name</td>...</tr></table>
  </form></td></tr>
</table>

I would remove the tables entirely and replace it with styled html elements like divs and spans.

How to update record using Entity Framework 6?

This code is the result of a test to update only a set of columns without making a query to return the record first. It uses Entity Framework 7 code first.

// This function receives an object type that can be a view model or an anonymous 
// object with the properties you want to change. 
// This is part of a repository for a Contacts object.

public int Update(object entity)
{
    var entityProperties =  entity.GetType().GetProperties();   
    Contacts con = ToType(entity, typeof(Contacts)) as Contacts;

    if (con != null)
    {
        _context.Entry(con).State = EntityState.Modified;
        _context.Contacts.Attach(con);

        foreach (var ep in entityProperties)
        {
            // If the property is named Id, don't add it in the update. 
            // It can be refactored to look in the annotations for a key 
            // or any part named Id.

            if(ep.Name != "Id")
                _context.Entry(con).Property(ep.Name).IsModified = true;
        }
    }

    return _context.SaveChanges();
}

public static object ToType<T>(object obj, T type)
{
    // Create an instance of T type object
    object tmp = Activator.CreateInstance(Type.GetType(type.ToString()));

    // Loop through the properties of the object you want to convert
    foreach (PropertyInfo pi in obj.GetType().GetProperties())
    {
        try
        {
            // Get the value of the property and try to assign it to the property of T type object
            tmp.GetType().GetProperty(pi.Name).SetValue(tmp, pi.GetValue(obj, null), null);
        }
        catch (Exception ex)
        {
            // Logging.Log.Error(ex);
        }
    }
    // Return the T type object:         
    return tmp;
}

Here is the complete code:

public interface IContactRepository
{
    IEnumerable<Contacts> GetAllContats();
    IEnumerable<Contacts> GetAllContactsWithAddress();
    int Update(object c);
}

public class ContactRepository : IContactRepository
{
    private ContactContext _context;

    public ContactRepository(ContactContext context)
    {
        _context = context;
    }

    public IEnumerable<Contacts> GetAllContats()
    {
        return _context.Contacts.OrderBy(c => c.FirstName).ToList();
    }

    public IEnumerable<Contacts> GetAllContactsWithAddress()
    {
        return _context.Contacts
            .Include(c => c.Address)
            .OrderBy(c => c.FirstName).ToList();
    }   

    //TODO Change properties to lambda expression
    public int Update(object entity)
    {
        var entityProperties = entity.GetType().GetProperties();

        Contacts con = ToType(entity, typeof(Contacts)) as Contacts;

        if (con != null)
        {
            _context.Entry(con).State = EntityState.Modified;
            _context.Contacts.Attach(con);

            foreach (var ep in entityProperties)
            {
                if(ep.Name != "Id")
                    _context.Entry(con).Property(ep.Name).IsModified = true;
            }
        }

        return _context.SaveChanges();
    }

    public static object ToType<T>(object obj, T type)
    {
        // Create an instance of T type object
        object tmp = Activator.CreateInstance(Type.GetType(type.ToString()));

        // Loop through the properties of the object you want to convert
        foreach (PropertyInfo pi in obj.GetType().GetProperties())
        {
            try
            {
                // Get the value of the property and try to assign it to the property of T type object
                tmp.GetType().GetProperty(pi.Name).SetValue(tmp, pi.GetValue(obj, null), null);
            }
            catch (Exception ex)
            {
                // Logging.Log.Error(ex);
            }
        }
        // Return the T type object
        return tmp;
    }
}    

public class Contacts
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Company { get; set; }
    public string Title { get; set; }
    public Addresses Address { get; set; }    
}

public class Addresses
{
    [Key]
    public int Id { get; set; }
    public string AddressType { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public State State { get; set; }
    public string PostalCode { get; set; }  
}

public class ContactContext : DbContext
{
    public DbSet<Addresses> Address { get; set; } 
    public DbSet<Contacts> Contacts { get; set; } 
    public DbSet<State> States { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connString = "Server=YourServer;Database=ContactsDb;Trusted_Connection=True;MultipleActiveResultSets=true;";
        optionsBuilder.UseSqlServer(connString);
        base.OnConfiguring(optionsBuilder);
    }
}

Which characters are valid/invalid in a JSON key name?

No. Any valid string is a valid key. It can even have " as long as you escape it:

{"The \"meaning\" of life":42}

There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.

Please initialize the log4j system properly warning

Alright, so I got it working by changing this

log4j.rootLogger=DebugAppender

to this

log4j.rootLogger=DEBUG, DebugAppender

Apparently you have to specify the logging level to the rootLogger first? I apologize if I wasted anyone's time.

Also, I decided to answer my own question because this wasn't a classpath issue.

Check that a input to UITextField is numeric only

In Swift 4:

let formatString = "12345"
if let number = Decimal(string:formatString){

    print("String contains only number")
}
else{
    print("String doesn't contains only number")
}

How to get image height and width using java?

You could use the Toolkit, no need for ImageIO

Image image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());
int width = image.getWidth(null);
int height = image.getHeight(null);

If you don't want to handle the loading of the image do

ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());
int height = imageIcon.getIconHeight();
int width = imageIcon.getIconWidth();

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

download and install visual studio 2008

Microsoft Visual Studio 2008 Service Pack 1 (iso)

http://www.microsoft.com/en-us/download/details.aspx?id=13276

http://download.microsoft.com/download/a/3/7/a371b6d1-fc5e-44f7-914c-cb452b4043a9/VS2008SP1ENUX1512962.iso

Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB

Supported Operating System

    Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
    Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
    Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
    On Windows Vista: 2.4 GHz CPU, 768 MB RAM
    Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.

How to add a ScrollBar to a Stackpanel

For horizontally oriented StackPanel, explicitly putting both the scrollbar visibilities worked for me to get the horizontal scrollbar.

    <ScrollViewer VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" >
        <StackPanel Orientation="Horizontal" />
    </ScrollViewer>

Python 3 string.join() equivalent?

Visit https://www.tutorialspoint.com/python/string_join.htm

s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))

ab cd ef

s="."
print(s.join(seq))

ab.cd.ef

how to measure running time of algorithms in python

The programming language doesn't matter; measuring the runtime complexity of an algorithm works the same way regardless of the language. Analysis of Algorithms by Stanford on Google Code University is a very good resource for teaching yourself how to analyze the runtime complexity of algorithms and code.

If all you want to do is measure the elapsed time that a function or section of code took to run in Python, then you can use the timeit or time modules, depending on how long the code needs to run.

Still Reachable Leak detected by Valgrind

Since there is some routine from the the pthread family on the bottom (but I don't know that particular one), my guess would be that you have launched some thread as joinable that has terminated execution.

The exit state information of that thread is kept available until you call pthread_join. Thus, the memory is kept in a loss record at program termination, but it is still reachable since you could use pthread_join to access it.

If this analysis is correct, either launch these threads detached, or join them before terminating your program.

Edit: I ran your sample program (after some obvious corrections) and I don't have errors but the following

==18933== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
--18933-- 
--18933-- used_suppression:      2 dl-hack3-cond-1
--18933-- used_suppression:      2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a

Since the dl- thing resembles much of what you see I guess that you see a known problem that has a solution in terms of a suppression file for valgrind. Perhaps your system is not up to date, or your distribution doesn't maintain these things. (Mine is ubuntu 10.4, 64bit)

Python - IOError: [Errno 13] Permission denied:

I had a same problem. In my case, the user did not have write permission to the destination directory. Following command helped in my case :

chmod 777 University

What does numpy.random.seed(0) do?

numpy.random.seed(0)
numpy.random.randint(10, size=5)

This produces the following output: array([5, 0, 3, 3, 7]) Again,if we run the same code we will get the same result.

Now if we change the seed value 0 to 1 or others:

numpy.random.seed(1)
numpy.random.randint(10, size=5)

This produces the following output: array([5 8 9 5 0]) but now the output not the same like above.

converting list to json format - quick and easy way

I would avoid rolling your own and use either:

System.Web.Script.JavascriptSerializer

or

JSON.net

Both will do an excellent job :)

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

How to set environment via `ng serve` in Angular 6

You can use command ng serve -c dev for development environment ng serve -c prod for production environment

while building also same applies. You can use ng build -c dev for dev build

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

Add a list item through javascript

Try something like this:

var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

Best way to check for "empty or null value"

If there may be empty trailing spaces, probably there isn't better solution. COALESCE is just for problems like yours.

How to use TLS 1.2 in Java 6

I also got a similar error when forced to use TLS1.2 for java 6. And I handled it thanks to this library:

  1. Clone Source Code: https://github.com/tobszarny/ssl-provider-jvm16

  2. Add Main Class:

    public static void main(String[] args) throws Exception {
        try {
            String apiUrl = "https://domain/api/query?test=123";
    
            URL myurl = new URL(apiUrl);
            HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
            con.setSSLSocketFactory(new TSLSocketConnectionFactory());
            int responseCode = con.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

Javascript switch vs. if...else if...else

  1. If there is a difference, it'll never be large enough to be noticed.
  2. N/A
  3. No, they all function identically.

Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.

401 Unauthorized: Access is denied due to invalid credentials

I realize this is an older post but I had the same error on IIS 8.5. Hopefully this can help another experiencing the same issue (I didn't see my issue outlined in other questions with a similar title).

Everything seemed set up correctly with the Application Pool Identity, but I continued to receive the error. After much digging, there is a setting for the anonymous user to use the credentials of the application pool identity or a specific user. For whatever reason, mine was defaulted to a specific user. Altering the setting to the App Pool Identity fixed the issue for me.

  1. IIS Manager ? Sites ? Website
  2. Double click "Authentication"
  3. Select Anonymous Authentication
  4. From the Actions panel, select Edit
  5. Select Application pool Identity and click ok

Hopefully this saves someone else some time!

How can I make a thumbnail <img> show a full size image when clicked?

The

<a href="image2.gif" ><img src="image1.gif"/></a>

technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.

Loop through files in a directory using PowerShell

Give this a try:

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" -Filter *.log | 
Foreach-Object {
    $content = Get-Content $_.FullName

    #filter and save content to the original file
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content $_.FullName

    #filter and save content to a new file 
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content ($_.BaseName + '_out.log')
}

What's the difference between lists enclosed by square brackets and parentheses in Python?

One interesting difference :

lst=[1]
print lst          // prints [1]
print type(lst)    // prints <type 'list'>

notATuple=(1)
print notATuple        // prints 1
print type(notATuple)  // prints <type 'int'>
                                         ^^ instead of tuple(expected)

A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).

How can I join on a stored procedure?

It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.

The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.

I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.

CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN 
(
  SELECT tenant.ID AS TenantID, 
       SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
  FROM tblTenant tenant
    LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
  GROUP BY tenant.ID
)

Now to use that function, in your SQL...

SELECT t.TenantName, 
       t.CarPlateNumber, 
       t.CarColor, 
       t.Sex, 
       t.SSNO, 
       t.Phone, 
       t.Memo,
       u.UnitNumber,
       p.PropertyName
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty p ON u.PropertyID = p.ID
    LEFT JOIN dbo.fnMyFunc() AS a
         ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber

If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY or CROSS OUTER APPLY.

Read up on that here.

Cheers

How To Get Selected Value From UIPickerView

Getting the selected title of a picker:

let component = 0
let row = picker.selectedRow(inComponent: component)
let title = picker.delegate?.pickerView?(picker, titleForRow: row, forComponent: component)

Getting or changing CSS class property with Javascript using DOM style

You don't need to add '.' in your class name. This will do

document.getElementsByClassName('col1')

Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.

Here is a working example

http://jsfiddle.net/J9LU8/

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

How to escape double quotes in JSON

When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

Bootstrap Carousel image doesn't align properly

While vekozlov's answer will work in Bootstrap 3 to center your image, it will break when the carousel is scaled down: the image retains its size instead of scaling down with the carousel.

Instead, do this on the top-level carousel div:

<div id="my-carousel" class="carousel slide"
    style="max-width: 900px; margin: 0 auto">
    ...
</div>

This will center the entire carousel and prevent it from growing beyond the width of your images (i.e. 900 px or whatever you want to set it to). However, when the carousel is scaled down the images scale down with it.

You should put this styling info in your CSS/LESS file, of course.

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Include the class that you are using Within your text file, then intelliSense will know where to look when you type within your text file. This works for me.

So it’s important to check the Unreal API to see where the included class is so that you have the path to type on the include line. Hope that makes sense.

PowerShell array initialization

You can also rely on the default value of the constructor if you wish to create a typed array:

> $a = new-object bool[] 5
> $a
False
False
False
False
False

The default value of a bool is apparently false so this works in your case. Likewise if you create a typed int[] array, you'll get the default value of 0.

Another cool way that I use to initialze arrays is with the following shorthand:

> $a = ($false, $false, $false, $false, $false)
> $a
False
False
False
False
False

Or if you can you want to initialize a range, I've sometimes found this useful:

> $a = (1..5)   
> $a
1
2
3
4
5

Hope this was somewhat helpful!

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I solved this on my WAMP setup by enabling the php_openssl extension, since the URL I was loading from used https://.

Comparing two vectors in an if statement

I'd probably use all.equal and which to get the information you want. It's not recommended to use all.equal in an if...else block for some reason, so we wrap it in isTRUE(). See ?all.equal for more:

foo <- function(A,B){
  if (!isTRUE(all.equal(A,B))){
    mismatches <- paste(which(A != B), collapse = ",")
    stop("error the A and B does not match at the following columns: ", mismatches )
  } else {
    message("Yahtzee!")
  }
}

And in use:

> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) : 
  error the A and B does not match at the following columns: 2,4

How to use the DropDownList's SelectedIndexChanged event

You should add AutoPostBack="true" to DropDownList1

                <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>

jQuery: serialize() form and other parameters

Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

var data = form.serialize() + '&' + $.param(object)

See http://api.jquery.com/jQuery.param for further reference.

How to include external Python code to use in other files?

I've found the python inspect module to be very useful

For example with teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

And from the another script or the python console

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.

Rounding to two decimal places in Python 2.7?

Use the built-in function round():

>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68

Or built-in function format():

>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'

Or new style string formatting:

>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'

Or old style string formatting:

>>> "%.2f" % (1.679)
'1.68'

help on round:

>>> print round.__doc__
round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number.  Precision may be negative.

Testing if value is a function

form.onsubmit will always be a function when defined as an attribute of HTML the form element. It's some sort of anonymous function attached to an HTML element, which has the this pointer bound to that FORM element and also has a parameter named event which will contain data about the submit event.

Under these circumstances I don't understand how you got a string as a result of a typeof operation. You should give more details, better some code.

Edit (as a response to your second edit):

I believe the handler attached to the HTML attribute will execute regardless of the above code. Further more, you could try to stop it somehow, but, it appears that FF 3, IE 8, Chrome 2 and Opera 9 are executing the HTML attribute handler in the first place and then the one attached (I didn't tested with jQuery though, but with addEventListener and attachEvent). So... what are you trying to accomplish exactly?

By the way, your code isn't working because your regular expression will extract the string "valid();", which is definitely not a function.

Is it possible to make desktop GUI application in .NET Core?

You could use Electron and wire it up with Edge.js resp. electron-edge. Edge.js allows Electron (Node.js) to call .NET DLL files and vice versa.

This way you can write the GUI with HTML, CSS and JavaScript and the backend with .NET Core. Electron itself is also cross platform and based on the Chromium browser.

The project cannot be built until the build path errors are resolved.

If you think you've done everything correctly but Eclipse still complains about the jars, refresh the folder where the jars are and make sure eclipse knows they've been added to the project. Specifying the file path alone is (apparently) not enough

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

What do I use for a max-heap implementation in Python?

The easiest way is to invert the value of the keys and use heapq. For example, turn 1000.0 into -1000.0 and 5.0 into -5.0.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.

You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.

Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.

Checking whether a variable is an integer or not

A more general approach that will attempt to check for both integers and integers given as strings will be

def isInt(anyNumberOrString):
    try:
        int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
        return True
    except ValueError :
        return False

isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

VBScript -- Using error handling

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.

AngularJS: How to make angular load script inside ng-include?

Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

Pandas read_csv low_memory and dtype options

As the error says, you should specify the datatypes when using the read_csv() method. So, you should write

file = pd.read_csv('example.csv', dtype='unicode')

How do I compile and run a program in Java on my Mac?

I will give you steps to writing and compiling code. Use this example:

 public class Paycheck {
    public static void main(String args[]) {
        double amountInAccount;
        amountInAccount = 128.57;
        System.out.print("You earned $");
        System.out.print(amountInAccount);
        System.out.println(" at work today.");
    }
}
  1. Save the code as Paycheck.java
  2. Go to terminal and type cd Desktop
  3. Type javac Paycheck.java
  4. Type java Paycheck
  5. Enjoy your program!

Passing command line arguments in Visual Studio 2010?

Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)

Greetings mic enter image description here

How do I use a PriorityQueue?

Java 8 solution

We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :

Using lambda expression

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> pq=
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
       // or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
        pq.add("Apple");
        pq.add("PineApple");
        pq.add("Custard Apple");
        while (pq.size() != 0)
        {
            System.out.println(pq.remove());
        }
    }

This will print:

Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:

PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                             Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:

PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:

default Comparator<T> reversed() {
    return Collections.reverseOrder(this);
}

offer() vs add()

As per the doc

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

Adding author name in Eclipse automatically to existing files

You can control select all customised classes and methods, and right-click, choose "Source", then select "Generate Element Comment". You should get what you want.

If you want to modify the Code Template then you can go to Preferences -- Java -- Code Style -- Code Templates, then do whatever you want.

Using a bitmask in C#

Easy Way:

[Flags]
public enum MyFlags {
    None = 0,
    Susan = 1,
    Alice = 2,
    Bob = 4,
    Eve = 8
}

To set the flags use logical "or" operator |:

MyFlags f = new MyFlags();
f = MyFlags.Alice | MyFlags.Bob;

And to check if a flag is included use HasFlag:

if(f.HasFlag(MyFlags.Alice)) { /* true */}
if(f.HasFlag(MyFlags.Eve)) { /* false */}

What is the "__v" field in Mongoose

Well, I can't see Tony's solution...so I have to handle it myself...


If you don't need version_key, you can just:

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default: Date.now}
}, {
    versionKey: false // You should be aware of the outcome after set to false
});

Setting the versionKey to false means the document is no longer versioned.

This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.

Since the array is now smaller, it may accidentally access the wrong subdocument in the array.

The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.

More information can be found at: http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Constants in Objective-C

I am generally using the way posted by Barry Wark and Rahul Gupta.

Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:

// file.h
extern NSString* const MyConst;

//file.m
NSString* const MyConst = @"Lorem ipsum";

Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.

I have a header file which defines the macro STR_CONST(name, value):

// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif

The in my .h/.m pair where I want to define the constant I do the following:

// myfile.h
#import <StringConsts.h>

STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");

// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"

et voila, I have all the information about the constants in .h file only.

Changing column names of a data frame

This may be helpful:

rename.columns=function(df,changelist){
  #renames columns of a dataframe
  for(i in 1:length(names(df))){
    if(length(changelist[[names(df)[i]]])>0){
      names(df)[i]= changelist[[names(df)[i]]]
    }
  }
  df
}

# Specify new dataframe
df=rename.columns(df,list(old.column='new.column.name'))

NodeJS/express: Cache and 304 status code

Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.

The empty page can be easily solved by using Shift key+reload button at the browser.

The empty page can be a result of:

  • a bug in your code
  • while testing you served an empty page (you can't remember) that is cached by the browser
  • a bug in Safari (if so, please report it to Apple and don't try to fix it yourself)

Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.

Enabling refreshing for specific html elements only

try to empty your innerHtml everytime. just like this:

_x000D_
_x000D_
Element.innerHtml="";
_x000D_
_x000D_
_x000D_

How do you style a TextInput in react native for password input

Add

secureTextEntry={true}

or just

secureTextEntry 

property in your TextInput.

Working Example:

<TextInput style={styles.input}
           placeholder="Password"
           placeholderTextColor="#9a73ef"
           returnKeyType='go'
           secureTextEntry
           autoCorrect={false}
/>

Window.open and pass parameters by post method

Instead of writing a form into the new window (which is tricky to get correct, with encoding of values in the HTML code), just open an empty window and post a form to it.

Example:

<form id="TheForm" method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something" />
<input type="hidden" name="more" value="something" />
<input type="hidden" name="other" value="something" />
</form>

<script type="text/javascript">
window.open('', 'TheWindow');
document.getElementById('TheForm').submit();
</script>

Edit:

To set the values in the form dynamically, you can do like this:

function openWindowWithPost(something, additional, misc) {
  var f = document.getElementById('TheForm');
  f.something.value = something;
  f.more.value = additional;
  f.other.value = misc;
  window.open('', 'TheWindow');
  f.submit();
}

To post the form you call the function with the values, like openWindowWithPost('a','b','c');.

Note: I varied the parameter names in relation to the form names to show that they don't have to be the same. Usually you would keep them similar to each other to make it simpler to track the values.

How can I convert ticks to a date format?

It's much simpler to do this:

DateTime dt = new DateTime(633896886277130000);

Which gives

dt.ToString() ==> "9/27/2009 10:50:27 PM"

You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

Not sure where you get October 1.

How can I record a Video in my Android App.?

You record audio and video using the same MediaRecorder class. It's pretty simple. Here's an example.

mongodb: insert if not exists

In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.

Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

How can I get query string values in JavaScript?

Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.

var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p=a[i].split('=', 2);
        if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));

IMPORTANT! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the current URL.

So what exactly changed? With url http://sb.com/reg/step1?param= results will be same. But with url http://sb.com/reg/step1?param Bruno's solution returns an object without keys, while mine returns an object with key param and undefined value.

Google Maps JavaScript API RefererNotAllowedMapError

I was attempting to use the Places API (Autocomplete) and had to also enable the Maps Javascript API from within Google Cloud Console before the Places API would work.

How do I ignore a directory with SVN?

Here's an example directory structure:

\project
    \source
    \cache
    \other

When in project you see that your cache directory is not added and shows up as such.

> svn st
M  source
?  cache

To set the ignore property, do

svn propset svn:ignore cache .

where svn:ignore is the name of the property you're setting, cache is the value of the property, and . is the directory you're setting this property on. It should be the parent directory of the cache directory that needs the property.

To check what properties are set:

> svn proplist
Properties on '.':
  svn:ignore

To see the value of svn:ignore:

> svn propget svn:ignore
cache

To delete properties previously set:

svn propdel svn:ignore

jQuery: Load Modal Dialog Contents via Ajax

var dialogName = '#dialog_XYZ';
$.ajax({
        url: "/ajax_pages/my_page.ext",
        data: {....},
        success: function(data) {
          $(dialogName ).remove();

          $('BODY').append(data);

          $(dialogName )
            .dialog(options.dialogOptions);
        }
});

The Ajax-Request load the Dialog, add them to the Body of the current page and open the Dialog.

If you only whant to load the content you can do:

var dialogName = '#dialog_XYZ';
$.ajax({
            url: "/ajax_pages/my_page.ext",
            data: {....},
            success: function(data) {
              $(dialogName).append(data);

              $(dialogName )
                .dialog(options.dialogOptions);
            }
});

How to remove the focus from a TextBox in WinForms?

Please try set TabStop to False for your view control which is not be focused.

For eg:

txtEmpID.TabStop = false;

Is Tomcat running?

wget url or curl url where url is a url of the tomcat server that should be available, for example: wget http://localhost:8080. Then check the exit code, if it's 0 - tomcat is up.

Adding an onclick event to a div element

Its possible, we can specify onclick event in

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
    document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
    document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

How to put a link on a button with bootstrap?

If you don't really need the button element, just move the classes to a regular link:

<div class="btn-group">
    <a href="/save/1" class="btn btn-primary active">
        <i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
    </a>
    <a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>

Conversely, you can also change a button to appear like a link:

<button type="button" class="btn btn-link">Link</button>

How to efficiently remove duplicates from an array without using Set

I feel Android Killer's idea is great, but I just wondered if we can leverage HashMap. So I did a little experiment. And I found HashMap seems faster than HashSet.

Here is code:

    int[] input = new int[1000000];

    for (int i = 0; i < input.length; i++) {
        Random random = new Random();
        input[i] = random.nextInt(200000);
    }

    long startTime1 = new Date().getTime();
    System.out.println("Set start time:" + startTime1);

    Set<Integer> resultSet = new HashSet<Integer>();

    for (int i = 0; i < input.length; i++) {
        resultSet.add(input[i]);
    }

    long endTime1 = new Date().getTime();
    System.out.println("Set end time:"+ endTime1);
    System.out.println("result of set:" + (endTime1 - startTime1));     
    System.out.println("number of Set:" + resultSet.size() + "\n");

    long startTime2 = new Date().getTime();
    System.out.println("Map start time:" + startTime1);

    Map<Integer, Integer> resultMap = new HashMap<Integer, Integer>();

    for (int i = 0; i < input.length; i++) {
        if (!resultMap.containsKey(input[i]))
            resultMap.put(input[i], input[i]);
    }

    long endTime2 = new Date().getTime();
    System.out.println("Map end Time:" + endTime2);
    System.out.println("result of Map:" + (endTime2 - startTime2));
    System.out.println("number of Map:" + resultMap.size());

Here is result:

Set start time:1441960583837
Set end time:1441960583917
result of set:80
number of Set:198652

Map start time:1441960583837
Map end Time:1441960583983
result of Map:66
number of Map:198652

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

There is a simple, easy and better approach, if we need to change only the color of hamburger/back icon.

It is better as it changes color only of desired icon, whereas colorControlNormal and android:textColorSecondary might affect other childviews of toolbar as well.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

How to kill zombie process

I tried:

ps aux | grep -w Z   # returns the zombies pid
ps o ppid {returned pid from previous command}   # returns the parent
kill -1 {the parent id from previous command}

this will work :)

Assign a class name to <img> tag instead of write it in css file?

Its depend. If you have more than two images in .column but you only need some images to have css applied then its better to add class to image directly instead of doing .column img{/*styling for image here*/}

In performance aspect i thing apply class to image is better because by doing so css will not look for possible child image.

Get current date, given a timezone in PHP?

I have created some simple function you can use to convert time to any timezone :

function convertTimeToLocal($datetime,$timezone='Europe/Dublin') {
        $given = new DateTime($datetime, new DateTimeZone("UTC"));
        $given->setTimezone(new DateTimeZone($timezone));
        $output = $given->format("Y-m-d"); //can change as per your requirement
        return $output;
}

Remove whitespaces inside a string in javascript

You can use Strings replace method with a regular expression.

"Hello World ".replace(/ /g, "");

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp

RegExp

  • / / - Regular expression matching spaces

  • g - Global flag; find all matches rather than stopping after the first match

_x000D_
_x000D_
const str = "H    e            l l       o  World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
_x000D_
_x000D_

Best way to find the intersection of multiple sets?

Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:

def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
    try:
        return set.intersection(*sets)
    except TypeError: # this is Python < 2.6 or no arguments
        pass

    try: a_set= sets[0]
    except IndexError: # no arguments
        return set() # return empty set

    return reduce(a_set.intersection, sets[1:])

Guido might dislike reduce, but I'm kind of fond of it :)

belongs_to through associations

My approach was to make a virtual attribute instead of adding database columns.

class Choice
  belongs_to :user
  belongs_to :answer

  # ------- Helpers -------
  def question
    answer.question
  end

  # extra sugar
  def question_id
    answer.question_id
  end
end

This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer from the db, and then question. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.

There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.

Deserialize JSON to ArrayList<POJO> using Jackson

This variant looks more simple and elegant.

CollectionType typeReference =
    TypeFactory.defaultInstance().constructCollectionType(List.class, Dto.class);
List<Dto> resultDto = objectMapper.readValue(content, typeReference);

Skip rows during csv import pandas

skip[1] will skip second line, not the first one.

How to handle the `onKeyPress` event in ReactJS?

render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events.

How do I use Assert to verify that an exception has been thrown?

I do not recommend using the ExpectedException attribute (since it's too constraining and error-prone) or to write a try/catch block in each test (since it's too complicated and error-prone). Use a well-designed assert method -- either provided by your test framework or write your own. Here's what I wrote and use.

public static class ExceptionAssert
{
    private static T GetException<T>(Action action, string message="") where T : Exception
    {
        try
        {
            action();
        }
        catch (T exception)
        {
            return exception;
        }
        throw new AssertFailedException("Expected exception " + typeof(T).FullName + ", but none was propagated.  " + message);
    }

    public static void Propagates<T>(Action action) where T : Exception
    {
        Propagates<T>(action, "");
    }

    public static void Propagates<T>(Action action, string message) where T : Exception
    {
        GetException<T>(action, message);
    }

    public static void Propagates<T>(Action action, Action<T> validation) where T : Exception
    {
        Propagates(action, validation, "");
    }

    public static void Propagates<T>(Action action, Action<T> validation, string message) where T : Exception
    {
        validation(GetException<T>(action, message));
    }
}

Example uses:

    [TestMethod]
    public void Run_PropagatesWin32Exception_ForInvalidExeFile()
    {
        (test setup that might propagate Win32Exception)
        ExceptionAssert.Propagates<Win32Exception>(
            () => CommandExecutionUtil.Run(Assembly.GetExecutingAssembly().Location, new string[0]));
        (more asserts or something)
    }

    [TestMethod]
    public void Run_PropagatesFileNotFoundException_ForExecutableNotFound()
    {
        (test setup that might propagate FileNotFoundException)
        ExceptionAssert.Propagates<FileNotFoundException>(
            () => CommandExecutionUtil.Run("NotThere.exe", new string[0]),
            e => StringAssert.Contains(e.Message, "NotThere.exe"));
        (more asserts or something)
    }

NOTES

Returning the exception instead of supporting a validation callback is a reasonable idea except that doing so makes the calling syntax of this assert very different than other asserts I use.

Unlike others, I use 'propagates' instead of 'throws' since we can only test whether an exception propagates from a call. We can't test directly that an exception is thrown. But I suppose you could image throws to mean: thrown and not caught.

FINAL THOUGHT

Before switching to this sort of approach I considered using the ExpectedException attribute when a test only verified the exception type and using a try/catch block if more validation was required. But, not only would I have to think about which technique to use for each test, but changing the code from one technique to the other as needs changed was not trivial effort. Using one consistent approach saves mental effort.

So in summary, this approach sports: ease-of-use, flexibility and robustness (hard to do it wrong).

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Support for the experimental syntax 'classProperties' isn't currently enabled

Solution for webpack project

I just solve this problem by adding @babel/plugin-proposal-class-properties into webpack config plugin. The module section of my webpack.config.js looks like this

module: {
    rules: [
        {
            test: path.join(__dirname, '.'),
            exclude: /(node_modules)/,
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env',
                          '@babel/react',{
                          'plugins': ['@babel/plugin-proposal-class-properties']}]
            }
        }
    ]
}

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

How do I print a list of "Build Settings" in Xcode project?

In case you would like to read/check your Target Build Settings in runtime using code, here is the way:

1) Add a Run Script:

cp ${PROJECT_FILE_PATH}/project.pbxproj ${CONFIGURATION_BUILD_DIR}/${EXECUTABLE_NAME}.app/BuildSetting.pbxproj 

It will copy the Target Build Settings file into your Main Bundle (will be called BuildSetting.pbxproj).

2) You can now check the contents of that file at any time in code:

NSString *thePathString = [[NSBundle mainBundle] pathForResource:@"BuildSetting" ofType:@"pbxproj"];
NSDictionary *theDictionary = [NSDictionary dictionaryWithContentsOfFile:thePathString];

Running a command as Administrator using PowerShell?

It turns out it was too easy. All you have to do is run a cmd as administrator. Then type explorer.exe and hit enter. That opens up Windows Explorer. Now right click on your PowerShell script that you want to run, choose "run with PowerShell" which will launch it in PowerShell in administrator mode.

It may ask you to enable the policy to run, type Y and hit enter. Now the script will run in PowerShell as administrator. In case it runs all red, that means your policy didn't take affect yet. Then try again and it should work fine.

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Put text at bottom of div

I think that's better to use flex boxes (compatibility) than the absolute position. Here's example from me in pure css.

_x000D_
_x000D_
.container{_x000D_
  background-color:green;_x000D_
  height:500px;_x000D_
  _x000D_
  /*FLEX BOX */_x000D_
  display: -ms-flexbox;_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -webkit-flex-direction: column;_x000D_
    -ms-flex-direction: column;_x000D_
    flex-direction: column;_x000D_
    -webkit-flex-wrap: nowrap;_x000D_
    -ms-flex-wrap: nowrap;_x000D_
    flex-wrap: nowrap;_x000D_
    -webkit-justify-content: flex-start;_x000D_
    -ms-flex-pack: start;_x000D_
    justify-content: flex-start;_x000D_
    -webkit-align-content: stretch;_x000D_
    -ms-flex-line-pack: stretch;_x000D_
    align-content: stretch;_x000D_
    -webkit-align-items: flex-start;_x000D_
    -ms-flex-align: start;_x000D_
    align-items: flex-start;_x000D_
}_x000D_
_x000D_
.elem1{_x000D_
  background-color:red;_x000D_
  padding:20px;_x000D_
  _x000D_
   /*FLEX BOX CHILD */_x000D_
 -webkit-order: 0;_x000D_
    -ms-flex-order: 0;_x000D_
    order: 0;_x000D_
    -webkit-flex: 0 1 auto;_x000D_
    -ms-flex: 0 1 auto;_x000D_
    flex: 0 1 auto;_x000D_
    -webkit-align-self: flex-end;_x000D_
    -ms-flex-item-align: end;_x000D_
    align-self: flex-end;_x000D_
 _x000D_
}
_x000D_
<div class="container">_x000D_
 TOP OF CONTAINER _x000D_
<div class="elem1">_x000D_
  Nam pretium turpis et arcu. Sed a libero. Sed mollis, eros et ultrices tempus, mauris ipsum aliquam libero, non adipiscing dolor urna a orci._x000D_
_x000D_
Mauris sollicitudin fermentum libero. Pellentesque libero tortor, tincidunt et, tincidunt eget, semper nec, quam. Quisque id mi._x000D_
_x000D_
Donec venenatis vulputate lorem. Maecenas ullamcorper, dui et placerat feugiat, eros pede varius nisi, condimentum viverra felis nunc et lorem. Curabitur vestibulum aliquam leo._x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default:

Put this code in onCreate() of your Application file:

try {
        ProviderInstaller.installIfNeeded(getApplicationContext());
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);
        sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
            | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

React / JSX Dynamic Component Name

For a wrapper component, a simple solution would be to just use React.createElement directly (using ES6).

import RaisedButton from 'mui/RaisedButton'
import FlatButton from 'mui/FlatButton'
import IconButton from 'mui/IconButton'

class Button extends React.Component {
  render() {
    const { type, ...props } = this.props

    let button = null
    switch (type) {
      case 'flat': button = FlatButton
      break
      case 'icon': button = IconButton
      break
      default: button = RaisedButton
      break
    }

    return (
      React.createElement(button, { ...props, disableTouchRipple: true, disableFocusRipple: true })
    )
  }
}

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

When your function is deterministic, you are safe to declare it to be deterministic. The location of "DETERMINISTIC" keyword is as follows.

enter image description here

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

We had this issue as the host server had been updated to use TLS V1.2 and we were connecting using standard SSL. This was an update made as part of pen testing of the sites. We saw the issue in code connection, but not browsers going to the wsdl. Below code resolved:

if (System.Net.ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls))
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Taken from here: How do I disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

Map a 2D array onto a 1D array

using row major example:

A(i,j) = a[i + j*ld]; // where ld is the leading dimension
                      // (commonly same as array dimension in i)

// matrix like notation using preprocessor hack, allows to hide indexing
#define A(i,j) A[(i) + (j)*ld]

double *A = ...;
size_t ld = ...;
A(i,j) = ...;
... = A(j,i);

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

"int cannot be dereferenced" in Java

Basically, you're trying to use int as if it was an Object, which it isn't (well...it's complicated)

id.equals(list[pos].getItemNumber())

Should be...

id == list[pos].getItemNumber()

Handling the TAB character in Java

Or you could just perform a trim() on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)

Maven Modules + Building a Single Specific Module

You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").

So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.

Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am or -pl command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)

Convert True/False value read from file to boolean

you can use distutils.util.strtobool

>>> from distutils.util import strtobool

>>> strtobool('True')
1
>>> strtobool('False')
0

True values are y, yes, t, true, on and 1; False values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

Best way to read a large file into a byte array in C#?

Use the BufferedStream class in C# to improve performance. A buffer is a block of bytes in memory used to cache data, thereby reducing the number of calls to the operating system. Buffers improve read and write performance.

See the following for a code example and additional explanation: http://msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx

Find indices of elements equal to zero in a NumPy array

If you are working with a one-dimensional array there is a syntactic sugar:

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.flatnonzero(x == 0)
array([1, 3, 5])

How to make button look like a link?

I think this is very easy to do with very few lines. here is my solution

_x000D_
_x000D_
.buttonToLink{
   background: none;
   border: none;
   color: red
}

.buttonToLink:hover{
   background: none;
   text-decoration: underline;
}
_x000D_
<button  class="buttonToLink">A simple link button</button>
_x000D_
_x000D_
_x000D_

How to increase size of DOSBox window?

  • go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.

  • run "DOSBox 0.74 Options.bat"

  • the script starts notepad with configuration file: here change

    windowresolution=1600x800

    output=ddraw

(the resolution can't be changed if output=surface - that's the default).

  • safe configuration file changes.

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

C# Parsing JSON array of objects

Use NewtonSoft JSON.Net library.

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

Hope this helps.

Can I use DIV class and ID together in CSS?

Of course you can.

Your HTML there is just fine. To style the elements with css you can use the following approaches:

#y {
    ...
}

.x {
    ...
}

#y.x {
    ...
}

Also you can add as many classes as you wish to your element

<div id="id" class="classA classB classC ...">
</div>

And you can style that element using a selector with any combination of the classes and id. For example:

#id.classA.classB.classC {
     ...
}

#id.classC {
}

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

What is a Python egg?

"Egg" is a single-file importable distribution format for Python-related projects.

"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."

Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.