Programs & Examples On #Winforms interop

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();

Which is better, return value or out parameter?

It's preference mainly

I prefer returns and if you have multiple returns you can wrap them in a Result DTO

public class Result{
  public Person Person {get;set;}
  public int Sum {get;set;}
}

PHP Warning: Unknown: failed to open stream

If you are running Fedora, make sure SELinux is not interfering.You fix this with this command:

    sudo /sbin/restorecon -R /var/www/. 

More info here: linuxquestions.org/questions/linux-server-73/

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

Android Push Notifications: Icon not displaying in notification, white square shown instead

Declare this code in Android Manifest :

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" 

android:resource="@drawable/ic_stat_name" />

I hope this useful to you.

How to write ternary operator condition in jQuery?

Here is a working example in side a function:

_x000D_
_x000D_
function setCurrency(){_x000D_
   var returnCurrent;_x000D_
   $("#RequestCurrencyType").is(":checked") === true ? returnCurrent = 'Dollar': returnCurrent = 'Euro';_x000D_
   _x000D_
   return returnCurrent;_x000D_
}
_x000D_
_x000D_
_x000D_

In your case. Change the selector and the return values

_x000D_
_x000D_
$("#blackbox").css('background-color') === 'pink' ? return "black" : return "pink";
_x000D_
_x000D_
_x000D_

lastly, to know what is the value used by the browser run the following in the console:

_x000D_
_x000D_
$("#blackbox").css('background-color')
_x000D_
_x000D_
_x000D_

and use the "rgb(xxx.xxx.xxx)" value instead of the Hex for the color selection.

How to make an AJAX call without jQuery?

<html>
  <script>
    var xmlDoc = null ;

  function load() {
    if (typeof window.ActiveXObject != 'undefined' ) {
      xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
      xmlDoc.onreadystatechange = process ;
    }
    else {
      xmlDoc = new XMLHttpRequest();
      xmlDoc.onload = process ;
    }
    xmlDoc.open( "GET", "background.html", true );
    xmlDoc.send( null );
  }

  function process() {
    if ( xmlDoc.readyState != 4 ) return ;
    document.getElementById("output").value = xmlDoc.responseText ;
  }

  function empty() {
    document.getElementById("output").value = '<empty>' ;
  }
</script>

<body>
  <textarea id="output" cols='70' rows='40'><empty></textarea>
  <br></br>
  <button onclick="load()">Load</button> &nbsp;
  <button onclick="empty()">Clear</button>
</body>
</html>

EditText request focus

Yes, I got the answer.. just simply edit the manifest file as:

        <activity android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateAlwaysVisible" />

and set EditText.requestFocus() in onCreate()..

Thanks..

LINQ Contains Case Insensitive

Honestly, this doesn't need to be difficult. It may seem that on the onset, but it's not. Here's a simple linq query in C# that does exactly as requested.

In my example, I'm working against a list of persons that have one property called FirstName.

var results = ClientsRepository().Where(c => c.FirstName.ToLower().Contains(searchText.ToLower())).ToList();

This will search the database on lower case search but return full case results.

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

This should work:

var result = cmd.ExecuteScalar();
conn.Close();

return result != null ? result.ToString() : string.Empty;

Also, I'd suggest using Parameters in your query, something like (just a suggestion):

var cmd = new SqlCommand
{
    Connection = conn,
    CommandType = CommandType.Text,
    CommandText = "select COUNT(idemp_atd) absentDayNo from td_atd where absentdate_atd between @sdate and @edate and idemp_atd=@idemp group by idemp_atd"
};

cmd.Parameters.AddWithValue("@sdate", sdate);
cmd.Parameters.AddWithValue("@edate", edate);
// etc ...

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

linux execute command remotely

 ssh user@machine 'bash -s' < local_script.sh

or you can just

 ssh user@machine "remote command to run" 

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

Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.

As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:

Target's Build Phases section w/ added Log Build Settings script phase

To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash and the command to export.  You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources.  Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.

The result is this incredibly helpful listing of current environment variables used for building:

Build Log output w/ export command's results

How to implement common bash idioms in Python?

As of 2015 and Python 3.4's release, there's now a reasonably complete user-interactive shell available at: http://xon.sh/ or https://github.com/scopatz/xonsh

The demonstration video does not show pipes being used, but they ARE supported when in the default shell mode.

Xonsh ('conch') tries very hard to emulate bash, so things you've already gained muscle memory for, like

env | uniq | sort -r | grep PATH

or

my-web-server 2>&1 | my-log-sorter

will still work fine.

The tutorial is quite lengthy and seems to cover a significant amount of the functionality someone would generally expect at a ash or bash prompt:

  • Compiles, Evaluates, & Executes!
  • Command History and Tab Completion
  • Help & Superhelp with ? & ??
  • Aliases & Customized Prompts
  • Executes Commands and/or *.xsh Scripts which can also be imported
  • Environment Variables including Lookup with ${}
  • Input/Output Redirection and Combining
  • Background Jobs & Job Control
  • Nesting Subprocesses, Pipes, and Coprocesses
  • Subprocess-mode when a command exists, Python-mode otherwise
  • Captured Subprocess with $(), Uncaptured Subprocess with $[], Python Evaluation with @()
  • Filename Globbing with * or Regular Expression Filename Globbing with Backticks

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

It seems like you can also use the patch command. Put the diff in the root of the repository and run patch from the command line.

patch -i yourcoworkers.diff

or

patch -p0 -i yourcoworkers.diff

You may need to remove the leading folder structure if they created the diff without using --no-prefix.

If so, then you can remove the parts of the folder that don't apply using:

patch -p1 -i yourcoworkers.diff

The -p(n) signifies how many parts of the folder structure to remove.

More information on creating and applying patches here.

You can also use

git apply yourcoworkers.diff --stat 

to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).

How to validate a date?

This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.

For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):

console.log(new Date(2009, 1, 29));

The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)

Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):

var isActualDate = function (month, day, year) {
    var tempDate = new Date(year, --month, day);
    return month === tempDate.getMonth();
};

This isn't a complete solution and doesn't take i18n into account but it could be made more robust.

Cannot execute script: Insufficient memory to continue the execution of the program

You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.

I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.

(This is the same answer I provided here)

How add class='active' to html menu with php

A very easy solution to this problem is to do this.

<ul>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
  <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>

Which will output

<ul>
  <li class="current"><a href="index.php">Home</a></li>
  <li class=""><a href="portfolio.php">Portfolio</a></li>
  <li class=""><a href="services.php">Services</a></li>
  <li class=""><a href="contact.php">Contact</a></li>
  <li class=""><a href="links.php">Links</a></li>
</ul>

SQL query to get the deadlocks in SQL SERVER 2008

You can use a deadlock graph and gather the information you require from the log file.

The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table.

SELECT  L.request_session_id AS SPID, 
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName, 
    P.object_id AS LockedObjectId, 
    L.resource_type AS LockedResource, 
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,        
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph

http://weblogs.sqlteam.com/mladenp/archive/2008/04/29/SQL-Server-2005-Get-full-information-about-transaction-locks.aspx

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Using ChildActionOnly in MVC

A little late to the party, but...

The other answers do a good job of explaining what effect the [ChildActionOnly] attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render @Html.Partial("_MyParialView") directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.

This can come in handy, for example, in _Layout.cshtml. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render @Html.Action in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout page need not have a model. It follows that all other view models need not inherit from any base view model.

I'm sure there are other reasons to use the [ChildActionOnly] attribute, but this seems like a good one to me, so I thought I'd share.

Group array items using object

You can do something like this:

function convert(items) {
    var result = [];

    items.forEach(function (element) {
        var existingElement = result.filter(function (item) {
            return item.group === element.group;
        })[0];

        if (existingElement) {
            existingElement.color.push(element.color);
        } else {
            element.color = [element.color];
            result.push(element);
        }

    });

    return result;
}

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

How to echo (or print) to the js console with php

This will work with either an array, an object or a variable and also escapes the special characters that may break your JS :

function debugToConsole($msg) { 
        echo "<script>console.log(".json_encode($msg).")</script>";
}

Edit : Added json_encode to the echo statement. This will prevent your script from breaking if there are quotes in your $msg variable.

Java - Access is denied java.io.FileNotFoundException

When you create a new File, you are supposed to provide the file name, not only the directory you want to put your file in.

Try with something like

File file = new File("D:/Data/" + item.getFileName());

PHP new line break in emails

When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be

str_replace("\n","<br/>",$str);

after adding this code you wont have to use pre tag for all the output oparation.

copyed this ans from this website :

sort files by date in PHP

An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.

$output = array();
foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {      
        if ( $value->isFile() ) {
            $output[] = array( $value->getMTime(), $value->getRealPath() );
        }
}

usort ( $output, function( $a, $b ) {
    return $a[0] > $b[0];
});

What's the difference between "git reset" and "git checkout"?

brief mnemonics:

git reset HEAD           :             index = HEAD
git checkout             : file_tree = index
git reset --hard HEAD    : file_tree = index = HEAD

Why catch and rethrow an exception in C#?

While many of the other answers provide good examples of why you might want to catch an rethrow an exception, no one seems to have mentioned a 'finally' scenario.

An example of this is where you have a method in which you set the cursor (for example to a wait cursor), the method has several exit points (e.g. if () return;) and you want to ensure the cursor is reset at the end of the method.

To do this you can wrap all of the code in a try/catch/finally. In the finally set the cursor back to the right cursor. So that you don't bury any valid exceptions, rethrow it in the catch.

try
{
    Cursor.Current = Cursors.WaitCursor;
    // Test something
    if (testResult) return;
    // Do something else
}
catch
{
    throw;
}
finally
{
     Cursor.Current = Cursors.Default;
}

Ruby function to remove all white spaces?

If you are using Rails/ActiveSupport, you can use squish method. It removes white space on both ends of the string and groups multiple white space to single space.

For eg.

" a  b  c ".squish

will result to:

"a b c"

Check this reference from api.rubyonrails.org.

How to change UIButton image in Swift

Swift 5

yourButton.setImage(UIImage(named: "BUTTON_FILENAME.png"), for: .normal)

How to check 'undefined' value in jQuery

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

function A(val){
  if(typeof(val)  === "undefined") 
    //do this
  else
   //do this
}

Submit form using a button outside the <form> tag

Similar to another solution here, with minor modification:

<form method="METHOD" id="FORMID">
   <!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>

https://www.w3schools.com/tags/att_form.asp

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

How to use a TRIM function in SQL Server

You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'

SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code], 
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title], 
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]

Play/pause HTML 5 video using JQuery

This is the easy methods we can use

on jquery button click function

$("#button").click(function(event){
    $('video').trigger('play');
    $('video').trigger('pause');
}

Thanks

How do I install Python 3 on an AWS EC2 instance?

If you do a

sudo yum list | grep python3

you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:

sudo yum install python34 python34-pip

Returning null in a method whose signature says return int?

The type int is a primitive and it cannot be null, if you want to return null, mark the signature as

public Integer pollDecrementHigherKey(int x) {
    x = 10;

    if (condition) {
        return x; // This is auto-boxing, x will be automatically converted to Integer
    } else if (condition2) {
        return null; // Integer inherits from Object, so it's valid to return null
    } else {
        return new Integer(x); // Create an Integer from the int and then return
    }
    
    return 5; // Also will be autoboxed and converted into Integer
}

Why doesn't Dijkstra's algorithm work for negative weight edges?

Correctness of Dijkstra's algorithm:

We have 2 sets of vertices at any step of the algorithm. Set A consists of the vertices to which we have computed the shortest paths. Set B consists of the remaining vertices.

Inductive Hypothesis: At each step we will assume that all previous iterations are correct.

Inductive Step: When we add a vertex V to the set A and set the distance to be dist[V], we must prove that this distance is optimal. If this is not optimal then there must be some other path to the vertex V that is of shorter length.

Suppose this some other path goes through some vertex X.

Now, since dist[V] <= dist[X] , therefore any other path to V will be atleast dist[V] length, unless the graph has negative edge lengths.

Thus for dijkstra's algorithm to work, the edge weights must be non negative.

ng-change get new value and original value

You could use a watch instead, because that has the old and new value, but then you're adding to the digest cycle.

I'd just keep a second variable in the controller and set that.

How to filter array in subdocument with MongoDB

Use $filter aggregation

Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.

db.test.aggregate([
    {$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
    {$project: {
        list: {$filter: {
            input: "$list",
            as: "list",
            cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
        }}
    }}
]);

insert data from one table to another in mysql

If you want insert all data from one table to another table there is a very simply sql

INSERT INTO destinationTable  (SELECT * FROM sourceDbName.SourceTableName);

How to change font size in html?

You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.

<p style="font-size: 28px;"> Hello, World! </p>

You can also set the color by setting:

<p style="color: blue;"> Hello, World! </p>

However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/

Where does Anaconda Python install on Windows?

C:\Users\<Username>\AppData\Local\Continuum\anaconda2

For me this was the default installation directory on Windows 7. Found it via Rusy's answer

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

iPhone is not available. Please reconnect the device

After trying all of the previous answers, the only thing that worked for me iOS 14.2 was to run Xcode 12.2 beta, and then switch back to Xcode 12.0.1 production.

How do I make the method return type generic?

Based on the same idea as Super Type Tokens, you could create a typed id to use instead of a string:

public abstract class TypedID<T extends Animal> {
  public final Type type;
  public final String id;

  protected TypedID(String id) {
    this.id = id;
    Type superclass = getClass().getGenericSuperclass();
    if (superclass instanceof Class) {
      throw new RuntimeException("Missing type parameter.");
    }
    this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
  }
}

But I think this may defeat the purpose, since you now need to create new id objects for each string and hold on to them (or reconstruct them with the correct type information).

Mouse jerry = new Mouse();
TypedID<Dog> spike = new TypedID<Dog>("spike") {};
TypedID<Duck> quacker = new TypedID<Duck>("quacker") {};

jerry.addFriend(spike, new Dog());
jerry.addFriend(quacker, new Duck());

But you can now use the class in the way you originally wanted, without the casts.

jerry.callFriend(spike).bark();
jerry.callFriend(quacker).quack();

This is just hiding the type parameter inside the id, although it does mean you can retrieve the type from the identifier later if you wish.

You'd need to implement the comparison and hashing methods of TypedID too if you want to be able to compare two identical instances of an id.

Encrypting & Decrypting a String in C#

using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}

Collapse all methods in Visual Studio Code

You should add user settings:

{
    "editor.showFoldingControls": "always",
    "editor.folding": true,
    "editor.foldingStrategy": "indentation", 
}

Hibernate JPA Sequence (non-Id)

If you are using postgresql
And i'm using in spring boot 1.5.6

@Column(columnDefinition = "serial")
@Generated(GenerationTime.INSERT)
private Integer orderID;

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I tried most of above. I was developing in Flutter so what worked for me was pub cache repair.

Detect if a NumPy array contains at least one non-numeric value?

This should be faster than iterating and will work regardless of shape.

numpy.isnan(myarray).any()

Edit: 30x faster:

import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
    'numpy.isnan(a).any()',
    'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
    print "  %.2f s" % timeit.Timer(m, s).timeit(1000), m

Results:

  0.11 s numpy.isnan(a).any()
  3.75 s any(numpy.isnan(x) for x in a.flatten())

Bonus: it works fine for non-array NumPy types:

>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Android studio 3.0

step0:

Close android studio

step1:

Goto C:\Program Files\Android\Android Studio\plugins\android\lib\templates\activities\common\root\res\layout\

step2:

Backup simple.xml.ftl

step3:

Change simple.xml.ftl to code below and save :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}">


<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="12dp"
    android:layout_marginTop="21dp"
    android:text="don't forget to click useful if this helps. this is my first post at stackoverflow!"
    android:textSize="20sp"
    />

</RelativeLayout>

How to delete columns in numpy.array

From Numpy Documentation

np.delete(arr, obj, axis=None) Return a new array with sub-arrays along an axis deleted.

>>> arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

>>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])

JMS Topic vs Queues

That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.

Custom ImageView with drop shadow

Use this class to draw shadow on bitmaps

public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mIconSize = Utils.convertDpToPixel(context,63);
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }



    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

This is how did it works like a charm.

CSS

#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;

background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}  

in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)


<div id="loader">
</div>

JS at the bottom of _layout file


<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
 $("#loader").fadeOut(1000);
</script>  

How do I remove repeated elements from ArrayList?

If you don't want duplicates, use a Set instead of a List. To convert a List to a Set you can use the following code:

// list is some List of Strings
Set<String> s = new HashSet<String>(list);

If really necessary you can use the same construction to convert a Set back into a List.

Powershell remoting with ip-address as target

On Windows 10 it is important to make sure the WinRM Service is running to invoke the command

* Set-Item wsman:\localhost\Client\TrustedHosts -value '*' -Force *

How to disable back swipe gesture in UINavigationController on iOS 7

All of these solutions manipulate Apple's gesture recognizer in a way they do not recommend. I've just been told by a friend that there's a better solution:

[navigationController.interactivePopGestureRecognizer requireGestureRecognizerToFail: myPanGestureRecognizer];

where myPanGestureRecognizer is the gesture recognizer you are using to e.g. show your menu. That way, Apple's gesture recognizer doesn't get turned back on by them when you push a new navigation controller and you don't need to rely on hacky delays that may fire too early if your phone is put to sleep or under heavy load.

Leaving this here because I know I'll not remember this the next time I need it, and then I'll have the solution to the issue here.

What is JSONP, and why was it created?

A simple example for the usage of JSONP.

client.html

    <html>
    <head>
   </head>
     body>


    <input type="button" id="001" onclick=gO("getCompany") value="Company"  />
    <input type="button" id="002" onclick=gO("getPosition") value="Position"/>
    <h3>
    <div id="101">

    </div>
    </h3>

    <script type="text/javascript">

    var elem=document.getElementById("101");

    function gO(callback){

    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://localhost/test/server.php?callback='+callback;
    elem.appendChild(script);
    elem.removeChild(script);


    }

    function getCompany(data){

    var message="The company you work for is "+data.company +"<img src='"+data.image+"'/   >";
    elem.innerHTML=message;
}

    function getPosition(data){
    var message="The position you are offered is "+data.position;
    elem.innerHTML=message;
    }
    </script>
    </body>
    </html>

server.php

  <?php

    $callback=$_GET["callback"];
    echo $callback;

    if($callback=='getCompany')
    $response="({\"company\":\"Google\",\"image\":\"xyz.jpg\"})";

    else
    $response="({\"position\":\"Development Intern\"})";
    echo $response;

    ?>    

How can I get the number of records affected by a stored procedure?

Turns out for me that SET NOCOUNT ON was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery(); always returned -1.

I just set it off: SET NOCOUNT OFF without needing to use @@ROWCOUNT.

More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete

Is there a simple way to delete a list element by value?

Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.

In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.

In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it

Then, Im used:

c = len(list)-1
for element in (reversed(list)):
    if condition(element):
        del list[c]
    c -= 1
print(list)

where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]

Also You can do more pythonic using enumerate:

for i, element in enumerate(reversed(list)):
    if condition(element):
        del list[(i+1)*-1]
print(list)

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

Add a helper class:

public static class Redirector {
        public static void RedirectTo(this Controller ct, string action) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
        }

        public static void RedirectTo(this Controller ct, string action, string controller) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
        }

        public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
        }
    }

Then call in your action:

this.RedirectTo("Index", "Cement");

Add javascript code to any global javascript included file or layout file to intercept all ajax requests:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  $(function() {_x000D_
    $(document).ajaxComplete(function (event, xhr, settings) {_x000D_
            var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
            if (urlHeader != null && urlHeader !== undefined) {_x000D_
                window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
            }_x000D_
        });_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to link a folder with an existing Heroku app

Use heroku's fork

  1. Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!

    heroku fork -a sourceapp targetapp
    
  2. Clone it local

    git clone [email protected]:youamazingapp.git
    
  3. Make a new repo on github and add it

    git remote add origin https://github.com/yourname/your_repo.git
    
  4. Push on github

    git push origin master
    

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

How do I set an absolute include path in PHP?

The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.

So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.

ini_set("include_path", "/your_include_path:".ini_get("include_path"));

This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

bower command not found

I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:

sudo npm install -g bower

How to use terminal commands with Github?

To add all file at a time, use git add -A

To check git whole status, use git log

How to add 10 minutes to my (String) time?

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :

14:10
14:20

wordpress contactform7 textarea cols and rows change in smaller screens

I was able to get this work. I added the following to my custom CSS:

.wpcf7-form textarea{ 
    width: 100% !important;
    height:50px;
}

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

Javascript receipt printing using POS Printer

I'm going out on a limb here , since your question was not very detailed, that a) your receipt printer is a thermal printer that needs raw data, b) that "from javascript" you are talking about printing from the web browser and c) that you do not have access to send raw data from browser

Here is a Java Applet that solves all that for you , if I'm correct about those assumptions then you need either Java, Flash, or Silverlight http://code.google.com/p/jzebra/

How to get row index number in R?

If i understand your question, you just want to be able to access items in a data frame (or list) by row:

x = matrix( ceiling(9*runif(20)), nrow=5  )   
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x)      # create a small data frame

df[1,]                  # get the first row
df[3,]                  # get the third row
df[nrow(df),]           # get the last row

lf = as.list(df)        

lf[[1]]                 # get first row
lf[[3]]                 # get third row

etc.

Why use the INCLUDE clause when creating an index?

You would use the INCLUDE to add one or more columns to the leaf level of a non-clustered index, if by doing so, you can "cover" your queries.

Imagine you need to query for an employee's ID, department ID, and lastname.

SELECT EmployeeID, DepartmentID, LastName
FROM Employee
WHERE DepartmentID = 5

If you happen to have a non-clustered index on (EmployeeID, DepartmentID), once you find the employees for a given department, you now have to do "bookmark lookup" to get the actual full employee record, just to get the lastname column. That can get pretty expensive in terms of performance, if you find a lot of employees.

If you had included that lastname in your index:

CREATE NONCLUSTERED INDEX NC_EmpDep 
  ON Employee(EmployeeID, DepartmentID)
  INCLUDE (Lastname)

then all the information you need is available in the leaf level of the non-clustered index. Just by seeking in the non-clustered index and finding your employees for a given department, you have all the necessary information, and the bookmark lookup for each employee found in the index is no longer necessary --> you save a lot of time.

Obviously, you cannot include every column in every non-clustered index - but if you do have queries which are missing just one or two columns to be "covered" (and that get used a lot), it can be very helpful to INCLUDE those into a suitable non-clustered index.

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Just some thoughts on my case.

If you have changed the dbPath and logPath dirs to your custom values (say /data/mongodb/data, /data/mongodb/log), you must chown them to mongodb user, otherwise, the non-existent /data/db/ dir will be used.

sudo chown -R mongodb:mongodb /data/mongodb/

sudo service mongod restart

Replacement for deprecated sizeWithFont: in iOS 7?

Better use automatic dimensions (Swift):

  tableView.estimatedRowHeight = 68.0
  tableView.rowHeight = UITableViewAutomaticDimension

NB: 1. UITableViewCell prototype should be properly designed (for the instance don't forget set UILabel.numberOfLines = 0 etc) 2. Remove HeightForRowAtIndexPath method

enter image description here

VIDEO: https://youtu.be/Sz3XfCsSb6k

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

Finding the length of an integer in C

int digits=1;

while (x>=10){
    x/=10;
    digits++;
}
return digits;

How do I pass a datetime value as a URI parameter in asp.net mvc?

You should first add a new route in global.asax:


routes.MapRoute(
                "MyNewRoute",
                "{controller}/{action}/{date}",
                new { controller="YourControllerName", action="YourActionName", date = "" }
            );

The on your Controller:



        public ActionResult MyActionName(DateTime date)
        {

        }

Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.

How to upgrade all Python packages with pip

This seems more concise.

pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U

Explanation:

pip list --outdated gets lines like these

urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]

In cut -d ' ' -f1, -d ' ' sets "space" as the delimiter, -f1 means to get the first column.

So the above lines becomes:

urllib3
wheel

then pass them to xargs to run the command, pip install -U, with each line as appending arguments

-n1 limits the number of arguments passed to each command pip install -U to be 1

Stored procedure - return identity as output parameter or scalar

I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.

How can I force gradle to redownload dependencies?

Only a manual deletion of the specific dependency in the cache folder works... an artifactory built by a colleague in enterprise repo.

Is there an alternative to string.Replace that is case-insensitive?

Here's an extension method. Not sure where I found it.

public static class StringExtensions
{
    public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
    {
        int startIndex = 0;
        while (true)
        {
            startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
            if (startIndex == -1)
                break;

            originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);

            startIndex += newValue.Length;
        }

        return originalString;
    }

}

Allow only numbers to be typed in a textbox

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />

SyntaxError: unexpected EOF while parsing

The SyntaxError: unexpected EOF while parsing means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100): and requires at least one line afterwards that contains code that should be in it.

It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3 but not for code blocks like for loops. See the following example:

In [1]: for i in range(100):
  File "<ipython-input-1-ece1e5c2587f>", line 1
    for i in range(100):
                        ^
SyntaxError: unexpected EOF while parsing

To avoid this error, you have to enter the whole code block as a single input:

In [2]: for i in range(5):
   ...:     print(i, end=', ')
0, 1, 2, 3, 4,

How can I see the size of files and directories in linux?

File Size in MB

ls -l --b=M  filename | cut -d " " -f5

File Size in GB

ls -l --b=G  filename | cut -d " " -f5

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

Is there a way to know your current username in mysql?

You can also use : mysql> select user,host from mysql.user;

+---------------+-------------------------------+
| user          | host                          |
+---------------+-------------------------------+
| fkernel       | %                             |
| nagios        | %                             |
| readonly      | %                             |
| replicant     | %                             |
| reporting     | %                             |
| reporting_ro  | %                             |
| nagios        | xx.xx.xx.xx                 |
| haproxy_root  | xx.xx.xx.xx
| root          | 127.0.0.1                     |
| nagios        | localhost                     |
| root          | localhost                     |
+---------------+-------------------------------+

jQuery trigger file input

adardesign nailed it regarding the file input element being ignored when it is hidden. I also noticed many people shifting element size to 0, or pushing it out of bounds with positioning and overflow adjustments. These are all great ideas.
An alternative way that also seems to work perfectly well is to just set the opacity to 0. Then you can always just set the position to keep it from offsetting other elements as hide does. It just seems a little unnecessary to shift an element nearly 10K pixels in any direction.

Here's a little example for those who want one:

input[type='file']{
    position:absolute;
    opacity:0;
    /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    /* For IE5 - 7 */
    filter: alpha(opacity=0);
}

What does a bitwise shift (left or right) do and what is it used for?

Left Shift

x = x * 2^value (normal operation)

x << value (bit-wise operation)


x = x * 16 (which is the same as 2^4)

The left shift equivalent would be x = x << 4

Right Shift

x = x / 2^value (normal arithmetic operation)

x >> value (bit-wise operation)


x = x / 8 (which is the same as 2^3)

The right shift equivalent would be x = x >> 3

Android: adb: Permission Denied

You might need to activate adb root from the developer settings menu. If you run adb root from the cmd line you can get:

root access is disabled by system setting - enable in settings -> development options

Once you activate the root option (ADB only or Apps and ADB) adb will restart and you will be able to use root from the cmd line.

A monad is just a monoid in the category of endofunctors, what's the problem?

That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.

The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.

But, I'll take a stab. The original sentence is this:

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

X here is a category. Endofunctors are functors from a category to itself (which is usually all Functors as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.

And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:

A monoid is...

  • A set, S
  • An operation, • : S × S ? S
  • An element of S, e : 1 ? S

...satisfying these laws:

  • (a • b) • c = a • (b • c), for all a, b and c in S
  • e • a = a • e = a, for all a in S

A monad is...

  • An endofunctor, T : X ? X (in Haskell, a type constructor of kind * -> * with a Functor instance)
  • A natural transformation, µ : T × T ? T, where × means functor composition (µ is known as join in Haskell)
  • A natural transformation, ? : I ? T, where I is the identity endofunctor on X (? is known as return in Haskell)

...satisfying these laws:

  • µ ° Tµ = µ ° µT
  • µ ° T? = µ ° ?T = 1 (the identity natural transformation)

With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.

How to handle iframe in Selenium WebDriver using java

To get back to the parent frame, use:

driver.switchTo().parentFrame();

To get back to the first/main frame, use:

driver.switchTo().defaultContent();

Save a file in json format using Notepad++

Simply you can save with extension .json but while saving you have to do some changes.

Change Save as type in red circle in image to All Files.

It will create .json file with name bharti.json.

To check this --> Right click at file --> Properties --> Type of file: JSON File (.json)

enter image description here

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

check if file exists on remote host with ssh

Test if a file exists:

HOST="example.com"
FILE="/path/to/file"

if ssh $HOST "test -e $FILE"; then
    echo "File exists."
else
    echo "File does not exist."
fi

And the opposite, test if a file does not exist:

HOST="example.com"
FILE="/path/to/file"

if ! ssh $HOST "test -e $FILE"; then
    echo "File does not exist."
else
    echo "File exists."
fi

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

if ($name )
{
    #since undef and '' both evaluate to false 
    #this should work only when string is defined and non-empty...
    #unless you're expecting someting like $name="0" which is false.
    #notice though that $name="00" is not false
}

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

Unfortunately MyApp has stopped. How can I solve this?

Crash during development

Try my favourite tool logview to get the logs and analyze them during development.
Make sure to mark ./logview and ./lib/logview.jar as executable when running in Linux.

If you don't like it, there're a lot of alternative desktop log viewers for Android.

Crash in the wild

Integrate a real-time crash reporting tool such as Firebase Crashlytics in order to get stacktraces of unhandled exceptions which occurred on users' devices.

Read How to Release a Buggy App (And Live to Tell the Tale) to know more about handling bugs in the field.

Change default timeout for mocha

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

How to pass in a react component into another react component to transclude the first component's content?

You can use this.props.children to render whatever children the component contains:

const Wrap = ({ children }) => <div>{children}</div>

export default () => <Wrap><h1>Hello word</h1></Wrap>

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Are you sure you are using correct SMTP server address?

Both smtp.google.com and smtp.gmail.com work, but SSL certificate is issued to the second one.

JavaScript load a page on button click

Just window.location = "http://wherever.you.wanna.go.com/", or, for local links, window.location = "my_relative_link.html".

You can try it by typing it into your address bar as well, e.g. javascript: window.location = "http://www.google.com/".

Also note that the protocol part of the URL (http://) is not optional for absolute links; omitting it will make javascript assume a relative link.

PHP PDO: charset, set names?

I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.

Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:

// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
  $this->exec('SET NAMES utf8');
}

Does Android keep the .apk files? if so where?

Preinstalled applications are in /system/app folder. User installed applications are in /data/app. I guess you can't access unless you have a rooted phone. I don't have a rooted phone here but try this code out:

public class Testing extends Activity {
    private static final String TAG = "TEST";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        File appsDir = new File("/data/app");

        String[] files = appsDir.list();

        for (int i = 0 ; i < files.length ; i++ ) {
            Log.d(TAG, "File: "+files[i]);

        }
    }

It does lists the apks in my rooted htc magic and in the emu.

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

C Linking Error: undefined reference to 'main'

You should provide output file name after -o option. In your case runexp.o is treated as output file name, not input object file and thus your main function is undefined.

Fetch first element which matches criteria

When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));

is incorrect syntax; but

this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));

is correct. Or:

this.stops.stream().filter(s -> s.getStation().getName().equals(name));

is also correct if the compiler has enough information to figure out the types.

Linux / Bash, using ps -o to get process by specific name?

Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do

pgrep -x PROCESS_NAME

-x          Require an exact match of the process name, or argument list if -f is given.
             The default is to match any substring.

This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.

Removing leading and trailing spaces from a string

neat and clean

 void trimLeftTrailingSpaces(string &input) {
        input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
            return !isspace(ch);
        }));
    }

    void trimRightTrailingSpaces(string &input) {
        input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
            return !isspace(ch);
        }).base(), input.end());
    }

css absolute position won't work with margin-left:auto margin-right: auto

if the absolute element has a width,you can use the code below

.divtagABS{
    width:300px;
    positon:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

Click outside menu to close in jquery

The stopPropagation options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.

Here is a simple solution based on user2989143's answer:

$('html').click(function(event) {
    if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
        $('#menu-container').hide();
    }
});

How to find files modified in last x minutes (find -mmin does not work as expected)

Manual of find:

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

   -amin n
          File was last accessed n minutes ago.

   -anewer file
          File was last accessed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points  to  is  always
          used.

   -atime n
          File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.

   -cmin n
          File's status was last changed n minutes ago.

   -cnewer file
          File's status was last changed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it  points
          to is always used.

   -ctime n
          File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

Example:

find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time

Simple GUI Java calculator

This is the working code...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class JavaCalculator extends JFrame {

    private JButton jbtNum1;
    private JButton jbtNum2;
    private JButton jbtNum3;
    private JButton jbtNum4;
    private JButton jbtNum5;
    private JButton jbtNum6;
    private JButton jbtNum7;
    private JButton jbtNum8;
    private JButton jbtNum9;
    private JButton jbtNum0;
    private JButton jbtEqual;
    private JButton jbtAdd;
    private JButton jbtSubtract;
    private JButton jbtMultiply;
    private JButton jbtDivide;
    private JButton jbtSolve;
    private JButton jbtClear;
    private double TEMP;
    private double SolveTEMP;
    private JTextField jtfResult;

    Boolean addBool = false;
    Boolean subBool = false;
    Boolean divBool = false;
    Boolean mulBool = false;

    String display = "";

    public JavaCalculator() {

        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(4, 3));
        p1.add(jbtNum1 = new JButton("1"));
        p1.add(jbtNum2 = new JButton("2"));
        p1.add(jbtNum3 = new JButton("3"));
        p1.add(jbtNum4 = new JButton("4"));
        p1.add(jbtNum5 = new JButton("5"));
        p1.add(jbtNum6 = new JButton("6"));
        p1.add(jbtNum7 = new JButton("7"));
        p1.add(jbtNum8 = new JButton("8"));
        p1.add(jbtNum9 = new JButton("9"));
        p1.add(jbtNum0 = new JButton("0"));
        p1.add(jbtClear = new JButton("C"));

        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(jtfResult = new JTextField(20));
        jtfResult.setHorizontalAlignment(JTextField.RIGHT);
        jtfResult.setEditable(false);

        JPanel p3 = new JPanel();
        p3.setLayout(new GridLayout(5, 1));
        p3.add(jbtAdd = new JButton("+"));
        p3.add(jbtSubtract = new JButton("-"));
        p3.add(jbtMultiply = new JButton("*"));
        p3.add(jbtDivide = new JButton("/"));
        p3.add(jbtSolve = new JButton("="));

        JPanel p = new JPanel();
        p.setLayout(new GridLayout());
        p.add(p2, BorderLayout.NORTH);
        p.add(p1, BorderLayout.SOUTH);
        p.add(p3, BorderLayout.EAST);

        add(p);

        jbtNum1.addActionListener(new ListenToOne());
        jbtNum2.addActionListener(new ListenToTwo());
        jbtNum3.addActionListener(new ListenToThree());
        jbtNum4.addActionListener(new ListenToFour());
        jbtNum5.addActionListener(new ListenToFive());
        jbtNum6.addActionListener(new ListenToSix());
        jbtNum7.addActionListener(new ListenToSeven());
        jbtNum8.addActionListener(new ListenToEight());
        jbtNum9.addActionListener(new ListenToNine());
        jbtNum0.addActionListener(new ListenToZero());

        jbtAdd.addActionListener(new ListenToAdd());
        jbtSubtract.addActionListener(new ListenToSubtract());
        jbtMultiply.addActionListener(new ListenToMultiply());
        jbtDivide.addActionListener(new ListenToDivide());
        jbtSolve.addActionListener(new ListenToSolve());
        jbtClear.addActionListener(new ListenToClear());
    } //JavaCaluclator()

    class ListenToClear implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //display = jtfResult.getText();
            jtfResult.setText("");
            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;

            TEMP = 0;
            SolveTEMP = 0;
        }
    }

    class ListenToOne implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "1");
        }
    }

    class ListenToTwo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "2");
        }
    }

    class ListenToThree implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "3");
        }
    }

    class ListenToFour implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "4");
        }
    }

    class ListenToFive implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "5");
        }
    }

    class ListenToSix implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "6");
        }
    }

    class ListenToSeven implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "7");
        }
    }

    class ListenToEight implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "8");
        }
    }

    class ListenToNine implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "9");
        }
    }

    class ListenToZero implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            display = jtfResult.getText();
            jtfResult.setText(display + "0");
        }
    }

    class ListenToAdd implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            addBool = true;
        }
    }

    class ListenToSubtract implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            subBool = true;
        }
    }

    class ListenToMultiply implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            mulBool = true;
        }
    }

    class ListenToDivide implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            TEMP = Double.parseDouble(jtfResult.getText());
            jtfResult.setText("");
            divBool = true;
        }
    }

    class ListenToSolve implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            SolveTEMP = Double.parseDouble(jtfResult.getText());
            if (addBool == true)
                SolveTEMP = SolveTEMP + TEMP;
            else if ( subBool == true)
                SolveTEMP = SolveTEMP - TEMP;
            else if ( mulBool == true)
                SolveTEMP = SolveTEMP * TEMP;
            else if ( divBool == true)
                            SolveTEMP = SolveTEMP / TEMP;
            jtfResult.setText(  Double.toString(SolveTEMP));

            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JavaCalculator calc = new JavaCalculator();
        calc.pack();
        calc.setLocationRelativeTo(null);
                calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        calc.setVisible(true);
    }

} //JavaCalculator

Split / Explode a column of dictionaries into separate columns with pandas

>>> df

   Station ID                        Pollutants
0        8809  {"a": "46", "b": "3", "c": "12"}
1        8810   {"a": "36", "b": "5", "c": "8"}
2        8811              {"b": "2", "c": "7"}
3        8812                       {"c": "11"}
4        8813            {"a": "82", "c": "15"}

speed comparison for a large dataset of 10 million rows

>>> df = pd.concat([df]*100000).reset_index(drop=True)
>>> df = pd.concat([df]*20).reset_index(drop=True)
>>> print(df.shape)
(10000000, 2)
def apply_drop(df):
    return df.join(df['Pollutants'].apply(pd.Series)).drop('Pollutants', axis=1)  

def json_normalise_drop(df):
    return df.join(pd.json_normalize(df.Pollutants)).drop('Pollutants', axis=1)  

def tolist_drop(df):
    return df.join(pd.DataFrame(df['Pollutants'].tolist())).drop('Pollutants', axis=1)  

def vlues_tolist_drop(df):
    return df.join(pd.DataFrame(df['Pollutants'].values.tolist())).drop('Pollutants', axis=1)  

def pop_tolist(df):
    return df.join(pd.DataFrame(df.pop('Pollutants').tolist()))  

def pop_values_tolist(df):
    return df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))

>>> %timeit apply_drop(df.copy())
1 loop, best of 3: 53min 20s per loop
>>> %timeit json_normalise_drop(df.copy())
1 loop, best of 3: 54.9 s per loop
>>> %timeit tolist_drop(df.copy())
1 loop, best of 3: 6.62 s per loop
>>> %timeit vlues_tolist_drop(df.copy())
1 loop, best of 3: 6.63 s per loop
>>> %timeit pop_tolist(df.copy())
1 loop, best of 3: 5.99 s per loop
>>> %timeit pop_values_tolist(df.copy())
1 loop, best of 3: 5.94 s per loop
+---------------------+-----------+
| apply_drop          | 53min 20s |
| json_normalise_drop |    54.9 s |
| tolist_drop         |    6.62 s |
| vlues_tolist_drop   |    6.63 s |
| pop_tolist          |    5.99 s |
| pop_values_tolist   |    5.94 s |
+---------------------+-----------+

df.join(pd.DataFrame(df.pop('Pollutants').values.tolist())) is the fastest

How do I make CMake output into a 'bin' dir?

Regardless of whether I define this in the main CMakeLists.txt or in the individual ones, it still assumes I want all the libs and bins off the main path, which is the least useful assumption of all.

Python: Best way to add to sys.path relative to the current running script

This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

Why do we need to install gulp globally and locally?

You can link the globally installed gulp locally with

npm link gulp

Best practice: PHP Magic Methods __set and __get

The best practice would be to use traditionnal getters and setters, because of introspection or reflection. There is a way in PHP (exactly like in Java) to obtain the name of a method or of all methods. Such a thing would return "__get" in the first case and "getFirstField", "getSecondField" in the second (plus setters).

More on that: http://php.net/manual/en/book.reflection.php

How to determine the current iPhone/device model?

Using a Swift 'switch-case':

func platformString() -> String {

    var devSpec: String

    switch platform() {

    case "iPhone1,2": devSpec = "iPhone 3G"
    case "iPhone2,1": devSpec = "iPhone 3GS"
    case "iPhone3,1": devSpec = "iPhone 4"
    case "iPhone3,3": devSpec = "Verizon iPhone 4"
    case "iPhone4,1": devSpec = "iPhone 4S"
    case "iPhone5,1": devSpec = "iPhone 5 (GSM)"
    case "iPhone5,2": devSpec = "iPhone 5 (GSM+CDMA)"
    case "iPhone5,3": devSpec = "iPhone 5c (GSM)"
    case "iPhone5,4": devSpec = "iPhone 5c (GSM+CDMA)"
    case "iPhone6,1": devSpec = "iPhone 5s (GSM)"
    case "iPhone6,2": devSpec = "iPhone 5s (GSM+CDMA)"
    case "iPhone7,1": devSpec = "iPhone 6 Plus"
    case "iPhone7,2": devSpec = "iPhone 6"
    case "iPod1,1": devSpec = "iPod Touch 1G"
    case "iPod2,1": devSpec = "iPod Touch 2G"
    case "iPod3,1": devSpec = "iPod Touch 3G"
    case "iPod4,1": devSpec = "iPod Touch 4G"
    case "iPod5,1": devSpec = "iPod Touch 5G"
    case "iPad1,1": devSpec = "iPad"
    case "iPad2,1": devSpec = "iPad 2 (WiFi)"
    case "iPad2,2": devSpec = "iPad 2 (GSM)"
    case "iPad2,3": devSpec = "iPad 2 (CDMA)"
    case "iPad2,4": devSpec = "iPad 2 (WiFi)"
    case "iPad2,5": devSpec = "iPad Mini (WiFi)"
    case "iPad2,6": devSpec = "iPad Mini (GSM)"
    case "iPad2,7": devSpec = "iPad Mini (GSM+CDMA)"
    case "iPad3,1": devSpec = "iPad 3 (WiFi)"
    case "iPad3,2": devSpec = "iPad 3 (GSM+CDMA)"
    case "iPad3,3": devSpec = "iPad 3 (GSM)"
    case "iPad3,4": devSpec = "iPad 4 (WiFi)"
    case "iPad3,5": devSpec = "iPad 4 (GSM)"
    case "iPad3,6": devSpec = "iPad 4 (GSM+CDMA)"
    case "iPad4,1": devSpec = "iPad Air (WiFi)"
    case "iPad4,2": devSpec = "iPad Air (Cellular)"
    case "iPad4,4": devSpec = "iPad mini 2G (WiFi)"
    case "iPad4,5": devSpec = "iPad mini 2G (Cellular)"

    case "iPad4,7": devSpec = "iPad mini 3 (WiFi)"
    case "iPad4,8": devSpec = "iPad mini 3 (Cellular)"
    case "iPad4,9": devSpec = "iPad mini 3 (China Model)"

    case "iPad5,3": devSpec = "iPad Air 2 (WiFi)"
    case "iPad5,4": devSpec = "iPad Air 2 (Cellular)"

    case "i386": devSpec = "Simulator"
    case "x86_64": devSpec = "Simulator"

    default: devSpec = "Unknown"
    }

    return devSpec
}

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Visual Studio displaying errors even if projects build

I've noticed that sometimes when switching git branches, Visual Studio (2017) will not recognize types from some files that had been added in the second branch. Deleting the .vs folder solves it, but it also trashes all your workspace settings. This trick seems to work well for me:

  1. Solution Explorer -> Find the file with the unrecognized class in it.
  2. Click Show All Files at the top of the Solution Explorer.
  3. Right-click the file -> Exclude from project.
  4. Right-click the file again -> Include in project.

This causes Intellisense to parse the file that it missed when switching branches.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

use of entityManager.createNativeQuery(query,foo.class)

That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).

for you you should do the following:

Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();

or if you want to use HQL you can do something like this:

Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();

Regards.

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

PHP Regex to get youtube video ID?

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);

This will account for

youtube.com/v/{vidid}
youtube.com/vi/{vidid}
youtube.com/?v={vidid}
youtube.com/?vi={vidid}
youtube.com/watch?v={vidid}
youtube.com/watch?vi={vidid}
youtu.be/{vidid}

I improved it slightly to support: http://www.youtube.com/v/5xADESocujo?feature=autoshare&version=3&autohide=1&autoplay=1

The line I use now is:

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches);

Git: How to pull a single file from a server repository in Git?

It is possible to do (in the deployed repository):

git fetch
// git fetch will download all the recent changes, but it will not put it in your current checked out code (working area).

Followed by:

git checkout origin/master -- path/to/file
// git checkout <local repo name (default is origin)>/<branch name> -- path/to/file will checkout the particular file from the downloaded changes (origin/master).

Why do we check up to the square root of a prime number to determine if it is prime?

A more intuitive explanation would be :-

The square root of 100 is 10. Let's say a x b = 100, for various pairs of a and b.

If a == b, then they are equal, and are the square root of 100, exactly. Which is 10.

If one of them is less than 10, the other has to be greater. For example, 5 x 20 == 100. One is greater than 10, the other is less than 10.

Thinking about a x b, if one of them goes down, the other must get bigger to compensate, so the product stays at 100. They pivot around the square root.

The square root of 101 is about 10.049875621. So if you're testing the number 101 for primality, you only need to try the integers up through 10, including 10. But 8, 9, and 10 are not themselves prime, so you only have to test up through 7, which is prime.

Because if there's a pair of factors with one of the numbers bigger than 10, the other of the pair has to be less than 10. If the smaller one doesn't exist, there is no matching larger factor of 101.

If you're testing 121, the square root is 11. You have to test the prime integers 1 through 11 (inclusive) to see if it goes in evenly. 11 goes in 11 times, so 121 is not prime. If you had stopped at 10, and not tested 11, you would have missed 11.

You have to test every prime integer greater than 2, but less than or equal to the square root, assuming you are only testing odd numbers.

`

Move UIView up when the keyboard appears in iOS

I found theDuncs answer very useful and below you can find my own (refactored) version:


Main Changes

  1. Now getting the keyboard size dynamically, rather than hard coding values
  2. Extracted the UIView Animation out into it's own method to prevent duplicate code
  3. Allowed duration to be passed into the method, rather than being hard coded

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    float newVerticalPosition = -keyboardSize.height;

    [self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
}


- (void)keyboardWillHide:(NSNotification *)notification {
    [self moveFrameToVerticalPosition:0.0f forDuration:0.3f];
}


- (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration {
    CGRect frame = self.view.frame;
    frame.origin.y = position;

    [UIView animateWithDuration:duration animations:^{
        self.view.frame = frame;
    }];
}

Defining TypeScript callback type

I came across the same error when trying to add the callback to an event listener. Strangely, setting the callback type to EventListener solved it. It looks more elegant than defining a whole function signature as a type, but I'm not sure if this is the correct way to do this.

class driving {
    // the answer from this post - this works
    // private callback: () => void; 

    // this also works!
    private callback:EventListener;

    constructor(){
        this.callback = () => this.startJump();
        window.addEventListener("keydown", this.callback);
    }

    startJump():void {
        console.log("jump!");
        window.removeEventListener("keydown", this.callback);
    }
}

MySQL ORDER BY rand(), name ASC

Use a subquery:

SELECT * FROM 
(
    SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name 

The inner query selects 20 users at random and the outer query orders the selected users by name.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

Here's my take experience with E7 async/await:

In case you have an async helperFunction() called from your test... (one explicilty with the ES7 async keyword, I mean)

? make sure, you call that as await helperFunction(whateverParams) (well, yeah, naturally, once you know...)

And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:

it('my test', async () => { ...

What was the strangest coding standard rule that you were forced to follow?

I've been getting worked up over naming table columns after mysql keywords. It requires stupid column name escaping in every single query you write.

SELECT this, that, `key` FROM sometable WHERE such AND suchmore;

Just horrible.

Eclipse : Maven search dependencies doesn't work

In your eclipse, go to Windows -> Preferences -> Maven Preferences Maven Screenshot Tick the option "Download repository index updates on startup". You may want to restart the eclipse.

Also go to Windows -> Show view -> Other -> Maven -> Maven repositories Maven Repository View Screenshot

On Maven repositories panel, Expand Global repositories then Right click on Central repositories and check "Full index enabled" option and then click on "Rebuild index".

Full Index Screenshot

Launching a website via windows commandline

Working from VaLo's answer:

cd %directory to browser%
%browser's name to main executable (firefox, chrome, opera, etc.)% https://www.google.com

start https://www.google.com doesn't seem to work (at least in my environment)

Creating a list of dictionaries results in a list of copies of the same dictionary

info is a pointer to a dictionary - you keep adding the same pointer to your list contact.

Insert info = {} into the loop and it should solve the problem:

...
content = []
for iframe in soup.find_all('iframe'):
    info = {}
    info['src'] = iframe.get('src')
    info['height'] = iframe.get('height')
    info['width'] = iframe.get('width')
...

Moving uncommitted changes to a new branch

Just create a new branch with git checkout -b ABC_1; your uncommitted changes will be kept, and you then commit them to that branch.

What is the command to truncate a SQL Server log file?

Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:

BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)

What is a Python equivalent of PHP's var_dump()?

So I have taken the answers from this question and another question and came up below. I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has. I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.

def dump(obj):
  '''return a printable representation of an object for debugging'''
  newobj=obj
  if '__dict__' in dir(obj):
    newobj=obj.__dict__
    if ' object at ' in str(obj) and not newobj.has_key('__type__'):
      newobj['__type__']=str(obj)
    for attr in newobj:
      newobj[attr]=dump(newobj[attr])
  return newobj

Here is the usage

class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'

from pprint import pprint
pprint(dump(obj))

and the results.

{'__type__': '<__main__.stdClass object at 0x2b126000b890>',
 'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
 'int': 1,
 'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
 'subObj': {'__type__': '<__main__.stdClass object at 0x2b126000b8d0>',
            'value': 'foobar'},
 'tup': (1, 2, 3, 4)}

Back button and refreshing previous activity

I would recommend overriding the onResume() method in activity number 1, and in there include code to refresh your array adapter, this is done by using [yourListViewAdapater].notifyDataSetChanged();

Read this if you are having trouble refreshing the list: Android List view refresh

Python PDF library

I already have used Reportlab in one project.

How to do SVN Update on my project using the command line

From the command line it would be just:

svn update

(in the directory you've got a copy of a SVN project).

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

  1. you need to create and id for the buttons you need to refference: btn1.setId(1);
  2. you can use the params variable to add parameters to your layout, i think the method is addRule(), check out the android java docs for this LayoutParams object.

Array vs ArrayList in performance

From here:

ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.


In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

How to get these two divs side-by-side?

Using flexbox it is super simple!

#parent_div_1, #parent_div_2, #parent_div_3 {
    display: flex;
}

Fiddle example

Removing duplicates from a list of lists

>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> import itertools
>>> k.sort()
>>> list(k for k,_ in itertools.groupby(k))
[[1, 2], [3], [4], [5, 6, 2]]

itertools often offers the fastest and most powerful solutions to this kind of problems, and is well worth getting intimately familiar with!-)

Edit: as I mention in a comment, normal optimization efforts are focused on large inputs (the big-O approach) because it's so much easier that it offers good returns on efforts. But sometimes (essentially for "tragically crucial bottlenecks" in deep inner loops of code that's pushing the boundaries of performance limits) one may need to go into much more detail, providing probability distributions, deciding which performance measures to optimize (maybe the upper bound or the 90th centile is more important than an average or median, depending on one's apps), performing possibly-heuristic checks at the start to pick different algorithms depending on input data characteristics, and so forth.

Careful measurements of "point" performance (code A vs code B for a specific input) are a part of this extremely costly process, and standard library module timeit helps here. However, it's easier to use it at a shell prompt. For example, here's a short module to showcase the general approach for this problem, save it as nodup.py:

import itertools

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

def doset(k, map=map, list=list, set=set, tuple=tuple):
  return map(list, set(map(tuple, k)))

def dosort(k, sorted=sorted, xrange=xrange, len=len):
  ks = sorted(k)
  return [ks[i] for i in xrange(len(ks)) if i == 0 or ks[i] != ks[i-1]]

def dogroupby(k, sorted=sorted, groupby=itertools.groupby, list=list):
  ks = sorted(k)
  return [i for i, _ in itertools.groupby(ks)]

def donewk(k):
  newk = []
  for i in k:
    if i not in newk:
      newk.append(i)
  return newk

# sanity check that all functions compute the same result and don't alter k
if __name__ == '__main__':
  savek = list(k)
  for f in doset, dosort, dogroupby, donewk:
    resk = f(k)
    assert k == savek
    print '%10s %s' % (f.__name__, sorted(resk))

Note the sanity check (performed when you just do python nodup.py) and the basic hoisting technique (make constant global names local to each function for speed) to put things on equal footing.

Now we can run checks on the tiny example list:

$ python -mtimeit -s'import nodup' 'nodup.doset(nodup.k)'
100000 loops, best of 3: 11.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort(nodup.k)'
100000 loops, best of 3: 9.68 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby(nodup.k)'
100000 loops, best of 3: 8.74 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.donewk(nodup.k)'
100000 loops, best of 3: 4.44 usec per loop

confirming that the quadratic approach has small-enough constants to make it attractive for tiny lists with few duplicated values. With a short list without duplicates:

$ python -mtimeit -s'import nodup' 'nodup.donewk([[i] for i in range(12)])'
10000 loops, best of 3: 25.4 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby([[i] for i in range(12)])'
10000 loops, best of 3: 23.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.doset([[i] for i in range(12)])'
10000 loops, best of 3: 31.3 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort([[i] for i in range(12)])'
10000 loops, best of 3: 25 usec per loop

the quadratic approach isn't bad, but the sort and groupby ones are better. Etc, etc.

If (as the obsession with performance suggests) this operation is at a core inner loop of your pushing-the-boundaries application, it's worth trying the same set of tests on other representative input samples, possibly detecting some simple measure that could heuristically let you pick one or the other approach (but the measure must be fast, of course).

It's also well worth considering keeping a different representation for k -- why does it have to be a list of lists rather than a set of tuples in the first place? If the duplicate removal task is frequent, and profiling shows it to be the program's performance bottleneck, keeping a set of tuples all the time and getting a list of lists from it only if and where needed, might be faster overall, for example.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

JavaScript by reference vs. by value

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

But, I think you already read it on SO; here you have the documentation you want:

http://snook.ca/archives/javascript/javascript_pass

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

Cited from

Apple Developer Relations 10-Oct-2014 09:12 PM

After much deliberation, engineering has removed this feature. The file /etc/launchd.conf was intentionally removed for security reasons. As a workaround, you could run launchctl limit as root early during boot, perhaps from a LaunchDaemon. (...)

Solution:

Put code in to /Library/LaunchDaemons/com.apple.launchd.limit.plist by bash-script:

#!/bin/bash

echo '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>eicar</string>
        <key>ProgramArguments</key>
        <array>
                <string>/bin/launchctl</string>
                <string>limit</string>
                <string>core</string>
                <string>unlimited</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
</dict>
</plist>' | sudo tee /Library/LaunchDaemons/com.apple.launchd.limit.plist

Unexpected token ILLEGAL in webkit

Also for the Google-fodder: check in your text editor whether the .js file is saved as Unicode and consider setting it to ANSI; also check if the linefeeds are set to DOS and consider switching them to Unix (depending on your server, of course).

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

The data received in your serialPort1_DataReceived method is coming from another thread context than the UI thread, and that's the reason you see this error.
To remedy this, you will have to use a dispatcher as descibed in the MSDN article:
How to: Make Thread-Safe Calls to Windows Forms Controls

So instead of setting the text property directly in the serialport1_DataReceived method, use this pattern:

delegate void SetTextCallback(string text);

private void SetText(string text)
{
  // InvokeRequired required compares the thread ID of the
  // calling thread to the thread ID of the creating thread.
  // If these threads are different, it returns true.
  if (this.textBox1.InvokeRequired)
  { 
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
  }
  else
  {
    this.textBox1.Text = text;
  }
}

So in your case:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
  txt += serialPort1.ReadExisting().ToString();
  SetText(txt.ToString());
}

How to safely open/close files in python 2.4

Here is example given which so how to use open and "python close

from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()

It's necessary to how many times you opened file have to close that times.

Appending HTML string to the DOM

Why is that not acceptable?

document.getElementById('test').innerHTML += str

would be the textbook way of doing it.

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

Pandas aggregate count distinct

Just adding to the answers already given, the solution using the string "nunique" seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M

%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s

%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s

%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s

What's the difference between a method and a function?

Function is the concept mainly belonging to Procedure oriented programming where a function is an an entity which can process data and returns you value

Method is the concept of Object Oriented programming where a method is a member of a class which mostly does processing on the class members.

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

Mac OS X and multiple Java versions

Manage multiple java version in MAC using jenv

  1. Install homebrew using following command

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

  1. install jenv and activate jenv

brew install jenv

echo 'eval "$(jenv init -)"' >> ~/.bash_profile

  1. tap cask-versions

brew tap homebrew/cask-versions

  1. search available java version that can be installed

brew search java

  1. E.g. to install java6 use following command

brew install cask java6

  1. Add multiple versions of java in jenv

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home

jenv add /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

Note:- if you get error like “”ln: /Users//.jenv/versions/oracle64-1.8.0.231: No such file or directory, then run following:-

mkdir -p /Users//.jenv/versions/oracle64-1.8.0.231

  1. Rehash jenv after adding jdk’s

jenv rehash

  1. List known versions of java to jenv

jenv versions

  1. Set default version

jenv global oracle64-1.8.0.231

  1. Change java version for a project

jenv local oracle64-1.6.0.65

  1. set JAVA_HOME with the same version as jenv

jenv exec bash

echo $JAVA_HOME

Display Bootstrap Modal using javascript onClick

A JavaScript function must first be made that holds what you want to be done:

function print() { console.log("Hello World!") }

and then that function must be called in the onClick method from inside an element:

<a onClick="print()"> ... </a>

You can learn more about modal interactions directly from the Bootstrap 3 documentation found here: http://getbootstrap.com/javascript/#modals

Your modal bind is also incorrect. It should be something like this, where "myModal" = ID of element:

$('#myModal').modal(options)

In other words, if you truly want to keep what you already have, put a "#" in front GSCCModal and see if that works.

It is also not very wise to have an onClick bound to a div element; something like a button would be more suitable.

Hope this helps!

Lock screen orientation (Android)

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

ImportError: cannot import name main when running pip --version command in windows7 32 bit

If you have a hardlink to pip in your PATH (i.e. if you have multiple python versions installed) and then you upgrade pip, you may also encounter this error.

The solution consists in creating the hardlink again. Or even better, stop using hardlinks and use softlinks.

Java: how to convert HashMap<String, Object> to array

If you want the keys and values, you can always do this via the entrySet:

hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]

From each entry you can (of course) get both the key and value via the getKey and getValue methods

Increment a database field by 1

I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

After going through other answers I came up with this, just apply class nested-counter-list to root ol tag:

sass code:

ol.nested-counter-list {
  counter-reset: item;

  li {
    display: block;

    &::before {
      content: counters(item, ".") ". ";
      counter-increment: item;
      font-weight: bold;
    }
  }

  ol {
    counter-reset: item;

    & > li {
      display: block;

      &::before {
        content: counters(item, ".") " ";
        counter-increment: item;
        font-weight: bold;
      }
    }
  }
}

css code:

ol.nested-counter-list {
  counter-reset: item;
}
ol.nested-counter-list li {
  display: block;
}
ol.nested-counter-list li::before {
  content: counters(item, ".") ". ";
  counter-increment: item;
  font-weight: bold;
}
ol.nested-counter-list ol {
  counter-reset: item;
}
ol.nested-counter-list ol > li {
  display: block;
}
ol.nested-counter-list ol > li::before {
  content: counters(item, ".") " ";
  counter-increment: item;
  font-weight: bold;
}

_x000D_
_x000D_
ol.nested-counter-list {
  counter-reset: item;
}

ol.nested-counter-list li {
  display: block;
}

ol.nested-counter-list li::before {
  content: counters(item, ".") ". ";
  counter-increment: item;
  font-weight: bold;
}

ol.nested-counter-list ol {
  counter-reset: item;
}

ol.nested-counter-list ol>li {
  display: block;
}

ol.nested-counter-list ol>li::before {
  content: counters(item, ".") " ";
  counter-increment: item;
  font-weight: bold;
}
_x000D_
<ol class="nested-counter-list">
  <li>one</li>
  <li>two
    <ol>
      <li>two.one</li>
      <li>two.two</li>
      <li>two.three</li>
    </ol>
  </li>
  <li>three
    <ol>
      <li>three.one</li>
      <li>three.two
        <ol>
          <li>three.two.one</li>
          <li>three.two.two</li>
        </ol>
      </li>
    </ol>
  </li>
  <li>four</li>
</ol>
_x000D_
_x000D_
_x000D_

And if you need trailing . at the end of the nested list's counters use this:

_x000D_
_x000D_
ol.nested-counter-list {
  counter-reset: item;
}

ol.nested-counter-list li {
  display: block;
}

ol.nested-counter-list li::before {
  content: counters(item, ".") ". ";
  counter-increment: item;
  font-weight: bold;
}

ol.nested-counter-list ol {
  counter-reset: item;
}
_x000D_
<ol class="nested-counter-list">
  <li>one</li>
  <li>two
    <ol>
      <li>two.one</li>
      <li>two.two</li>
      <li>two.three</li>
    </ol>
  </li>
  <li>three
    <ol>
      <li>three.one</li>
      <li>three.two
        <ol>
          <li>three.two.one</li>
          <li>three.two.two</li>
        </ol>
      </li>
    </ol>
  </li>
  <li>four</li>
</ol>
_x000D_
_x000D_
_x000D_

Binding IIS Express to an IP Address

Below are the complete changes I needed to make to run my x64 bit IIS application using IIS Express, so that it was accessible to a remote host:

iisexpress /config:"C:\Users\test-user\Documents\IISExpress\config\applicationhost.config" /site:MyWebSite
Starting IIS Express ...
Successfully registered URL "http://192.168.2.133:8080/" for site "MyWebSite" application "/"
Registration completed for site "MyWebSite"
IIS Express is running.
Enter 'Q' to stop IIS Express

The configuration file (applicationhost.config) had a section added as follows:

<sites>
  <site name="MyWebsite" id="2">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
      <virtualDirectory path="/" physicalPath="C:\build\trunk\MyWebsite" />
    </application>
    <bindings>
      <binding protocol="http" bindingInformation=":8080:192.168.2.133" />
    </bindings>
  </site>

The 64 bit version of the .NET framework can be enabled as follows:

<globalModules>
    <!--
        <add name="ManagedEngine" image="%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness32" />
        <add name="ManagedEngineV4.0_32bit" image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness32" />
    -->             
    <add name="ManagedEngine64" image="%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness64" />

Get the short Git version hash

I have Git version 2.7.4 with the following settings:

git config --global log.abbrevcommit yes
git config --global core.abbrev 8

Now when I do:

git log --pretty=oneline

I get an abbreviated commit id of eight digits:

ed054a38 add project based .gitignore
30a3fa4c add ez version
0a6e9015 add logic for shifting days
af4ab954 add n days ago
...

css divide width 100% to 3 column

As it's 2018, use flexbox - no more inline-block whitespace issues:

_x000D_
_x000D_
body {
  margin: 0;
}

#wrapper {
  display: flex;
  height: 200px;
}

#wrapper > div {
  flex-grow: 1;
}

#wrapper > div:first-of-type { background-color: red }
#wrapper > div:nth-of-type(2) { background-color: blue }
#wrapper > div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
  <div id="c1"></div>
  <div id="c2"></div>
  <div id="c3"></div>
</div>
_x000D_
_x000D_
_x000D_

Or even CSS grid if you are creating a grid.

_x000D_
_x000D_
body {
  margin: 0;
}

#wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: minmax(200px, auto);
}

#wrapper>div:first-of-type { background-color: red }
#wrapper>div:nth-of-type(2) { background-color: blue }
#wrapper>div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
  <div id="c1"></div>
  <div id="c2"></div>
  <div id="c3"></div>
</div>
_x000D_
_x000D_
_x000D_


Use CSS calc():

_x000D_
_x000D_
body {
  margin: 0;
}

div {
  height: 200px;
  width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */
  width: calc(100% / 3);
  display: inline-block;
}

div:first-of-type { background-color: red }
div:nth-of-type(2) { background-color: blue }
div:nth-of-type(3) { background-color: green }
_x000D_
<div></div><div></div><div></div>
_x000D_
_x000D_
_x000D_

JSFiddle


References:

Can an ASP.NET MVC controller return an Image?

Read the image, convert it to byte[], then return a File() with a content type.

public ActionResult ImageResult(Image image, ImageFormat format, string contentType) {
  using (var stream = new MemoryStream())
    {
      image.Save(stream, format);
      return File(stream.ToArray(), contentType);
    }
  }
}

Here are the usings:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.AspNetCore.Mvc;

Filter values only if not null using lambda in Java8

Leveraging the power of java.util.Optional#map():

List<Car> requiredCars = cars.stream()
  .filter (car -> 
    Optional.ofNullable(car)
      .map(Car::getName)
      .map(name -> name.startsWith("M"))
      .orElse(false) // what to do if either car or getName() yields null? false will filter out the element
    )
  .collect(Collectors.toList())
;

nodemon not found in npm

First install nodemon to your working folder by

npm install nodemon

Add the path of nodemon to the path variable of Environment Variable of System environment. In my case the path of nodemon was.

C:\Users\Dell\Desktop\Internship Project\schema\node_modules\.bin

It worked for me.

jQuery checkbox event handling

There are several useful answers, but none seem to cover all the latest options. To that end all my examples also cater for the presence of matching label elements and also allow you to dynamically add checkboxes and see the results in a side-panel (by redirecting console.log).

  • Listening for click events on checkboxes is not a good idea as that will not allow for keyboard toggling or for changes made where a matching label element was clicked. Always listen for the change event.

  • Use the jQuery :checkbox pseudo-selector, rather than input[type=checkbox]. :checkbox is shorter and more readable.

  • Use is() with the jQuery :checked pseudo-selector to test for whether a checkbox is checked. This is guaranteed to work across all browsers.

Basic event handler attached to existing elements:

$('#myform :checkbox').change(function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/2/

Notes:

  • Uses the :checkbox selector, which is preferable to using input[type=checkbox]
  • This connects only to matching elements that exist at the time the event was registered.

Delegated event handler attached to ancestor element:

Delegated event handlers are designed for situations where the elements may not yet exist (dynamically loaded or created) and is very useful. They delegate responsibility to an ancestor element (hence the term).

$('#myform').on('change', ':checkbox', function () {
    if ($(this).is(':checked')) {
        console.log($(this).val() + ' is now checked');
    } else {
        console.log($(this).val() + ' is now unchecked');
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/4/

Notes:

  • This works by listening for events (in this case change) to bubble up to a non-changing ancestor element (in this case #myform).
  • It then applies the jQuery selector (':checkbox' in this case) to only the elements in the bubble chain.
  • It then applies the event handler function to only those matching elements that caused the event.
  • Use document as the default to connect the delegated event handler, if nothing else is closer/convenient.
  • Do not use body to attach delegated events as it has a bug (to do with styling) that can stop it getting mouse events.

The upshot of delegated handlers is that the matching elements only need to exist at event time and not when the event handler was registered. This allows for dynamically added content to generate the events.

Q: Is it slower?

A: So long as the events are at user-interaction speeds, you do not need to worry about the negligible difference in speed between a delegated event handler and a directly connected handler. The benefits of delegation far outweigh any minor downside. Delegated event handlers are actually faster to register as they typically connect to a single matching element.


Why doesn't prop('checked', true) fire the change event?

This is actually by design. If it did fire the event you would easily get into a situation of endless updates. Instead, after changing the checked property, send a change event to the same element using trigger (not triggerHandler):

e.g. without trigger no event occurs

$cb.prop('checked', !$cb.prop('checked'));

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/5/

e.g. with trigger the normal change event is caught

$cb.prop('checked', !$cb.prop('checked')).trigger('change');

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/6/

Notes:

  • Do not use triggerHandler as was suggested by one user, as it will not bubble events to a delegated event handler.

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/8/

although it will work for an event handler directly connected to the element:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/u8bcggfL/9/

Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Reference: http://api.jquery.com/triggerhandler/

If anyone has additional features they feel are not covered by this, please do suggest additions.

Domain Account keeping locking out with correct password every few minutes

Download Microsoft Account Lockout Tools. Use LockoutStatus to find the last DC that didn't pre-authenticate the user that is having issues. Note date and time. Log into that DC, find that timeframe and check Client Address. Logoff from those servers.

How to print a groupby object

I found a tricky way, just for brainstorm, see the code:

df['a'] = df['A']  # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)
print(df)

the output:

             B
A     a
one   one    0
      one    1
      one    5
three three  3
      three  4
two   two    2

The pros is so easy to print, as it returns a dataframe, instead of Groupby Object. And the output looks nice. While the con is that it create a series of redundant data.

Unit testing with mockito for constructors

Once again the problem with unit-testing comes from manually creating objects using new operator. Consider passing already created Second instead:

class First {

  private Second second;

  public First(int num, Second second) {
    this.second = second;
    this.num = num;
  }

  // some other methods...
}

I know this might mean major rewrite of your API, but there is no other way. Also this class doesn't have any sense:

Mockito.when(new Second(any(String.class).thenReturn(null)));

First of all Mockito can only mock methods, not constructors. Secondly, even if you could mock constructor, you are mocking constructor of just created object and never really doing anything with that object.

Where is the Java SDK folder in my computer? Ubuntu 12.04

Location of JRE in Ubuntu:

/usr/lib/jvm/java-7-oracle/jre

reading text file with utf-8 encoding using java

Ok, I am definitively late to the party but if you are still looking for an optimal solution I would use the following ( for Java 8 )

    Charset inputCharset = Charset.forName("ISO-8859-1");
    Path pathToFile = ....
    try (BufferedReader br = Files.newBufferedReader( pathToFile, inputCharset )) {
        ...
     }

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

Detect changed input text box

try keyup instead of change.

<script type="text/javascript">
   $(document).ready(function () {
       $('#inputDatabaseName').keyup(function () { alert('test'); });
   });
</script>

Here's the official jQuery documentation for .keyup().

SQL query for today's date minus two months

SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

Rename multiple files in a folder, add a prefix (Windows)

I know it's an old question but I learned alot from the various answers but came up with my own solution as a function. This should dynamically add the parent folder as a prefix to all files that matches a certain pattern but only if it does not have that prefix already.

function Add-DirectoryPrefix($pattern) {
    # To debug, replace the Rename-Item with Select-Object
    Get-ChildItem -Path .\* -Filter $pattern -Recurse | 
        Where-Object {$_.Name -notlike ($_.Directory.Name + '*')} | 
        Rename-Item -NewName {$_.Directory.Name + '-' + $_.Name}
        # Select-Object -Property Directory,Name,@{Name = 'NewName'; Expression= {$_.Directory.Name + '-' + $_.Name}}
}

https://gist.github.com/kmpm/4f94e46e569ae0a4e688581231fa9e00

Should 'using' directives be inside or outside the namespace?

Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.

using ThisNamespace.IsImported.InAllNamespaces.Here;

namespace Namespace1
{ 
   using ThisNamespace.IsImported.InNamespace1.AndNamespace2;

   namespace Namespace2
   { 
      using ThisNamespace.IsImported.InJustNamespace2;
   }       
}

namespace Namespace3
{ 
   using ThisNamespace.IsImported.InJustNamespace3;
}

github: server certificate verification failed

You can also disable SSL verification, (if the project does not require a high level of security other than login/password) by typing :

git config --global http.sslverify false

enjoy git :)

How to hide a status bar in iOS?

Put this code to your view controller in which you hide status bar:

- (BOOL)prefersStatusBarHidden {return YES;}

How to know/change current directory in Python shell?

you want

import os
os.getcwd()
os.chdir('..')

Android XML Percent Symbol

Per google official documentation, use %1$s and %2$s http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Hello, %1$s! You have %2$d new messages.