Programs & Examples On #Loose typing

Deleting queues in RabbitMQ

In RabbitMQ versions > 3.0, you can also utilize the HTTP API if the rabbitmq_management plugin is enabled. Just be sure to set the content-type to 'application/json' and provide the vhost and queue name:

I.E. Using curl with a vhost 'test' and queue name 'testqueue':

$ curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/test/testqueue
HTTP/1.1 204 No Content
Server: MochiWeb/1.1 WebMachine/1.9.0 (someone had painted it blue)
Date: Tue, 16 Apr 2013 10:37:48 GMT
Content-Type: application/json
Content-Length: 0

Generic Property in C#

You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.

Encode String to UTF-8

In a moment I went through this problem and managed to solve it in the following way

first i need to import

import java.nio.charset.Charset;

Then i had to declare a constant to use UTF-8 and ISO-8859-1

private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Charset ISO = Charset.forName("ISO-8859-1");

Then I could use it in the following way:

String textwithaccent="Thís ís a text with accent";
String textwithletter="Ñandú";

text1 = new String(textwithaccent.getBytes(ISO), UTF_8);
text2 = new String(textwithletter.getBytes(ISO),UTF_8);

Set width to match constraints in ConstraintLayout

match_parent is not allowed. But you can actually set width and height to 0dp and set either top and bottom or left and right constraints to "parent".

So for example if you want to have the match_parent constraint on the width of the element, you can do it like this:

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

What does "exited with code 9009" mean during this build?

Another variant:

today I call python interpreter from cron in win32 and take ExitCode (%ERRORLEVEL%) 9009, because system account used by cron don't have path to Python directory.

Why does instanceof return false for some literals?

 typeof(text) === 'string' || text instanceof String; 

you can use this, it will work for both case as

  1. var text="foo"; // typeof will work

  2. String text= new String("foo"); // instanceof will work

How to stop the Timer in android?

It says timer() is not available on android? You might find this article useful.

http://developer.android.com/resources/articles/timed-ui-updates.html


I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:

schedule(TimerTask task, Date when) // Schedule a task for single execution.

Or you cancel it after the first execution:

cancel()  // Cancels the Timer and all scheduled tasks.

http://developer.android.com/reference/java/util/Timer.html

Get/pick an image from Android's built-in Gallery app programmatically

basis with the above code, I reflected the code like below, may be it's more suitable:

public String getPath(Uri uri) {
    String selectedImagePath;
    //1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if(cursor != null){
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        selectedImagePath = cursor.getString(column_index);
    }else{
        selectedImagePath = null;
    }

    if(selectedImagePath == null){
        //2:OI FILE Manager --- call method: uri.getPath()
        selectedImagePath = uri.getPath();
    }
    return selectedImagePath;
}

How to refresh the data in a jqGrid?

Try this to reload jqGrid with new data

jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

Session variables not working php

The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.

session_set_cookie_params(0)

is there a post render callback for Angular JS directive?

None of the solutions worked for me accept from using a timeout. This is because I was using a template that was dynamically being created during the postLink.

Note however, there can be a timeout of '0' as the timeout adds the function being called to the browser's queue which will occur after the angular rendering engine as this is already in the queue.

Refer to this: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering

jquery-ui-dialog - How to hook into dialog close event

I believe you can also do it while creating the dialog (copied from a project I did):

dialog = $('#dialog').dialog({
    modal: true,
    autoOpen: false,
    width: 700,
    height: 500,
    minWidth: 700,
    minHeight: 500,
    position: ["center", 200],
    close: CloseFunction,
    overlay: {
        opacity: 0.5,
        background: "black"
    }
});

Note close: CloseFunction

jQuery - find table row containing table cell containing specific text

You can use filter() to do that:

var tableRow = $("td").filter(function() {
    return $(this).text() == "foo";
}).closest("tr");

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

Can I use an image from my local file system as background in HTML?

Jeff Bridgman is correct. All you need is
background: url('pic.jpg')
and this assumes that pic is in the same folder as your html.

Also, Roberto's answer works fine. Tested in Firefox, and IE. Thanks to Raptor for adding formatting that displays full picture fit to screen, and without scrollbars... In a folder f, on the desktop is this html and a picture, pic.jpg, using your userid. Make those substitutions in the below:

<html>
<head>
    <style>
        body {

        background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;

        background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
        -webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
        -moz-background-size: cover; /* optional for Firefox 3.6 */ 
        -o-background-size: cover; /* for Opera 9.5 */
        margin: 0; /* to remove the default white margin of body */
        padding: 0; /* to remove the default white margin of body */
        overflow: hidden;
             }
    </style>
</head>
<body>
hello
</body>
</html>

How do I remove an object from an array with JavaScript?

I use this quite a bit so I created a small prototype. Simply looks for the item then pulls it out if there is a match.

//Prototype to remove object from array, removes first
//matching object only
Array.prototype.remove = function (v) {
    if (this.indexOf(v) != -1) {
        this.splice(this.indexOf(v), 1);
        return true;
    }
    return false;
}

Can be called like:

var arr = [12, 34, 56];
arr.remove(34);

The result would be [12, 56]

Has a boolean return if there was a successful remove, false if the element didn't exist.

how to get the current working directory's absolute path from irb

As for the path relative to the current executing script, since Ruby 2.0 you can also use

__dir__

So this is basically the same as

File.dirname(__FILE__)

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

Pick images of root folder from sub-folder

Your index.html can just do src="images/logo.png" and from sub.html you would do src="../images/logo.png"

remove all special characters in java

Your problem is that the indices returned by match.start() correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c every time, these indices become incorrect.

The best approach to solve this is to use replaceAll, for example:

        System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));

Automated Python to Java translation

It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).

Is there a performance difference between a for loop and a for-each loop?

All these loops do the exact same, I just want to show these before throwing in my two cents.

First, the classic way of looping through List:

for (int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ }

Second, the preferred way since it's less error prone (how many times have YOU done the "oops, mixed the variables i and j in these loops within loops" thing?).

for (String s : strings) { /* do something using s */ }

Third, the micro-optimized for loop:

int size = strings.size();
for (int i = -1; ++i < size;) { /* do something using strings.get(i) */ }

Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.

While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java for-each loop (some refer to it as Iterator loop and others as for-in loop) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.

If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.

How to extract duration time from ffmpeg output?

In case of one request parameter it is simplier to use mediainfo and its output formatting like this (for duration; answer in milliseconds)

mediainfo --Output="General;%Duration%" ~/work/files/testfiles/+h263_aac.avi 

outputs

24840

How can I force clients to refresh JavaScript files?

My colleague just found a reference to that method right after I posted (in reference to css) at http://www.stefanhayden.com/blog/2006/04/03/css-caching-hack/. Good to see that others are using it and it seems to work. I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?

Global keyboard capture in C# application

My rep is too low to comment, but concerning the CallbackOnCollectedDelegate exception, I modified the public void SetupKeyboardHooks() in C4d's answer to look like this:

public void SetupKeyboardHooks(out object hookProc)
{
  _globalKeyboardHook = new GlobalKeyboardHook();
  _globalKeyboardHook.KeyboardPressed += OnKeyPressed;


  hookProc = _globalKeyboardHook.GcSafeHookProc;
}

where GcSafeHookProc is just a public getter for _hookProc in OPs

_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

and stored the hookProc as a private field in the class calling the SetupKeyboardHooks(...), therefore keeping the reference alive, save from garbage collection, no more CallbackOnCollectedDelegate exception. Seems having this additional reference in the GlobalKeyboardHook class is not sufficient. Maybe make sure that this reference is also disposed when closing your app.

How do I create a basic UIButton programmatically?

This is an example as well to create three buttons. Just move their location.

UIImage *buttonOff = [UIImage imageNamed:@"crysBallNorm.png"];
UIImage *buttonOn = [UIImage imageNamed:@"crysBallHigh.png"];

UIButton *predictButton = [UIButton alloc];
predictButton = [UIButton buttonWithType:UIButtonTypeCustom];
predictButton.frame = CGRectMake(180.0, 510.0, 120.0, 30.0);
[predictButton setBackgroundImage:buttonOff forState:UIControlStateNormal];
[predictButton setBackgroundImage:buttonOn forState:UIControlStateHighlighted];
[predictButton setTitle:@"Predict" forState:UIControlStateNormal];
[predictButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
[predictButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:predictButton];

How to view the SQL queries issued by JPA?

If you want to see the exact queries altogether with parameter values and return values you can use a jdbc proxy driver. It will intercept all jdbc calls and log their values. Some proxies:

  • log4jdbc
  • jdbcspy

They may also provide some additional features, like measuring execution time for queries and gathering statistics.

Set a:hover based on class

One common error is leaving a space before the class names. Even if this was the correct syntax:

.menu a:hover .main-nav-item

it never would have worked.

Therefore, you would not write

.menu a .main-nav-item:hover

it would be

.menu a.main-nav-item:hover

Reading content from URL with Node.js

A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)

function httpGet(url) {
  return new Promise((resolve, reject) => {
    const http = require('http'),
      https = require('https');

    let client = http;

    if (url.toString().indexOf("https") === 0) {
      client = https;
    }

    client.get(url, (resp) => {
      let chunks = [];

      // A chunk of data has been recieved.
      resp.on('data', (chunk) => {
        chunks.push(chunk);
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {
        resolve(Buffer.concat(chunks));
      });

    }).on("error", (err) => {
      reject(err);
    });
  });
}

(async(url) => {
  var buf = await httpGet(url);
  console.log(buf.toString('utf-8'));
})('https://httpbin.org/headers');

1067 error on attempt to start MySQL

In my instance it had nothing to do with spaces in the file name. I used the MSI installer custom configuration and opted to exclude the default databases, assuming it was just something like Northwind/Adventureworks. Nope, it includes the core MySql system database... once I added that to the installation it worked.

Maximum execution time in phpMyadmin

Go to xampp/php/php.ini

Find this line:

max_execution_time=30

And change its value to any number you want. Restart Apache.

How can I pop-up a print dialog box using Javascript?

window.print();  

unless you mean a custom looking popup.

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

Confirmation before closing of tab/browser

If you want to ask based on condition:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

I feel like this has been well covered, maybe except for the following:

  • Simple KEY / INDEX (or otherwise called SECONDARY INDEX) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.

  • Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.

  • If you feel like your data should be UNIQUE, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.

  • You can only use FULLTEXT (or otherwise called SEARCH INDEX) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines

  • You can only use FULLTEXT on CHAR, VARCHAR and TEXT column types

  • FULLTEXT index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

how to resolve DTS_E_OLEDBERROR. in ssis

Knowing the version of Windows and SQL Server might be helpful in some cases. From the Native Client 10.0 I infer either SQL Server 2008 or SQL Server 2008 R2.

There are a few possible things to check, but I would check to see if 'priority boost' was configured on the SQL Server. This is a deprecated setting and will eventually be removed. The problem is that it can rob the operating system of needed resources. See the notes at:

http://msdn.microsoft.com/en-in/library/ms180943(v=SQL.105).aspx

If 'priority boost' has been configured to 1, then get it configured back to 0.

exec sp_configure 'priority boost', 0;
RECONFIGURE;

Give column name when read csv file pandas

If we are directly use data from csv it will give combine data based on comma separation value as it is .csv file.

user1 = pd.read_csv('dataset/1.csv')

If you want to add column names using pandas, you have to do something like this. But below code will not show separate header for your columns.

col_names=['TIME', 'X', 'Y', 'Z'] 
user1 = pd.read_csv('dataset/1.csv', names=col_names)

To solve above problem we have to add extra filled which is supported by pandas, It is header=None

user1 = pd.read_csv('dataset/1.csv', names=col_names, header=None)

Can I loop through a table variable in T-SQL?

I didn't know about the WHILE structure.

The WHILE structure with a table variable, however, looks similar to using a CURSOR, in that you still have to SELECT the row into a variable based on the row IDENTITY, which is effectively a FETCH.

Is there any difference between using WHERE and something like the following?

DECLARE @table1 TABLE ( col1 int )  
INSERT into @table1 SELECT col1 FROM table2

DECLARE cursor1 CURSOR  
    FOR @table1
OPEN cursor1  
FETCH NEXT FROM cursor1

I don't know if that's even possible. I suppose you might have to do this:

DECLARE cursor1 CURSOR  
    FOR SELECT col1 FROM @table1
OPEN cursor1  
FETCH NEXT FROM cursor1

Thanks for you help!

Opening a CHM file produces: "navigation to the webpage was canceled"

"unblocking" the file fixes the problem. Screenshot:

enter image description here

CSS / HTML Navigation and Logo on same line

You need to apply the logo class to the image...then float the ul

Codepen Demo

HTML

<img class="logo" src="http://i.imgur.com/hCrQkJi.png">

CSS

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  float: left;
  background: white;
}

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

What Java ORM do you prefer, and why?

Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.

It's even been ported to .NET (NHibernate) so you can use it there too.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think that it's around 2GB. While the answer by Pete Kirkham is very interesting and probably holds truth, I have allocated upwards of 3GB without error, however it did not use 3GB in practice. That might explain why you were able to allocate 2.5 GB on 2GB RAM with no swap space. In practice, it wasn't using 2.5GB.

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

can not find module "@angular/material"

I followed each of the suggestions here (I'm using Angular 7), but nothing worked. My app refused to acknowledge that @angular/material existed, so it showed an error on this line:

import { MatCheckboxModule } from '@angular/material';

Even though I was using the --save parameter to add Angular Material to my project:

npm install --save @angular/material @angular/cdk

...it refused to add anything to my "package.json" file.

I even tried deleting the package-lock.json file, as some articles suggest that this causes problems, but this had no effect.

To fix this issue, I had to manually add these two lines to my "package.json" file.

{
    "devDependencies": {
        ...
        "@angular/material": "~7.2.2",
        "@angular/cdk": "~7.2.2",
        ...

What I can't tell is whether this is an issue related to using Angular 7, or if it's been around for years....

Function to calculate distance between two coordinates

I implemeneted this algorithm in typescript and ES6

export type Coordinate = {
  lat: number;
  lon: number;
};

get the distance between two points:

function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
  if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
    return 0;
  }

  const radlat1 = (Math.PI * cord1.lat) / 180;
  const radlat2 = (Math.PI * cord2.lat) / 180;

  const theta = cord1.lon - cord2.lon;
  const radtheta = (Math.PI * theta) / 180;

  let dist =
    Math.sin(radlat1) * Math.sin(radlat2) +
    Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);

  if (dist > 1) {
    dist = 1;
  }

  dist = Math.acos(dist);
  dist = (dist * 180) / Math.PI;
  dist = dist * 60 * 1.1515;
  dist = dist * 1.609344; //convert miles to km
  
  return dist;
}

get the distance between an array of coordinates

export function getTotalDistance(coordinates: Coordinate[]) {
  coordinates = coordinates.filter((cord) => {
    if (cord.lat && cord.lon) {
      return true;
    }
  });
  
  let totalDistance = 0;

  if (!coordinates) {
    return 0;
  }

  if (coordinates.length < 2) {
    return 0;
  }

  for (let i = 0; i < coordinates.length - 2; i++) {
    if (
      !coordinates[i].lon ||
      !coordinates[i].lat ||
      !coordinates[i + 1].lon ||
      !coordinates[i + 1].lat
    ) {
      totalDistance = totalDistance;
    }
    totalDistance =
      totalDistance +
      getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
  }

  return totalDistance.toFixed(2);
}

Check if a file exists locally using JavaScript only

You can use this

function LinkCheck(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

jquery .live('click') vs .click()

There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:

$(this).children().live('click',doSomething);

It needs a selector to work properly because of the way events bubble up the DOM tree.

Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live and bind are both deprecated. You can perform both with .on(), which IMO is a much clearer syntax. To replace bind:

$(selector).on('click', function () {
    ...
});

and to replace live:

$(document).on('click', selector, function () {
    ...
});

Instead of using $(document), you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.

TypeError: 'builtin_function_or_method' object is not subscriptable

I think you want

listb.pop()[0]

The expression listb.pop is a valid python expression which results in a reference to the pop method, but doesn't actually call that method. You need to add the open and close parentheses to call the method.

jQuery.ajax handling continue responses: "success:" vs ".done"?

From JQuery Documentation

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Read Session Id using Javascript

you can probably ping the server via ajax inside javascript. The php file might look something like:

<?php
session_start();
$id = session_id();
echo $id;
?>

This will return you the current session id. Was this what you were looking for.

How to delete columns in numpy.array

>>> A = array([[ 1,  2,  3,  4],
               [ 5,  6,  7,  8],
               [ 9, 10, 11, 12]])

>>> A = A.transpose()

>>> A = A[1:].transpose()

Anaconda version with Python 3.5

To highlight a few points:

The docs recommend using an install environment: https://conda.io/docs/user-guide/install/download.html#choosing-a-version-of-anaconda-or-miniconda

The version archive is here: https://repo.continuum.io/archive/

The version history is here: https://docs.anaconda.com/anaconda/release-notes

"Anaconda3 then its python 3.x and if it is Anaconda2 then its 2.x" - +1 papbiceps

The version archive is sorted newest at the top, but Anaconda2 ABOVE Anaconda3.

In Python how should I test if a variable is None, True or False

There are many good answers. I would like to add one more point. A bug can get into your code if you are working with numerical values, and your answer is happened to be 0.

a = 0 
b = 10 
c = None

### Common approach that can cause a problem

if not a:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if not b:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}")

if not c:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")
Answer is not found. Answer is 0.   
Answer is: 10.   
Answer is not found. Answer is None.
### Safer approach 
if a is None:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if b is None:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}.")

if c is None:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")

Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.

Remove a parameter to the URL with JavaScript

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

The var alteredURL will be the output you desire.

Hope it helps!

Cannot assign requested address using ServerSocket.socketBind

Java documentation for java.net.BindExcpetion,

Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned.

Cause:

The error is due to the second condition mentioned above. When you start a server(Tomcat,Jetty etc) it listens to a port and bind a socket to an address and port. In Windows and Linux the hostname is resolved to IP address from /etc/hosts This host to IP address mapping file can be found at C:\Windows\System32\Drivers\etc\hosts. If this mapping is changed and the host name cannot be resolved to the IP address you get the error message.

Solution:

Edit the hosts file and correct the mapping for hostname and IP using admin privileges.

eg:

#127.0.0.1 localhost
192.168.52.1 localhost

Read more: java.net.BindException : cannot assign requested address.

Determine path of the executing script

Steamer25's approach works, but only if there is no whitespace in the path. On macOS at least the cmdArgs[match] returns something like /base/some~+~dir~+~with~+~whitespace/ for /base/some\ dir\ with\ whitespace/.

I worked around this by replacing the "~+~" with a simple whitespace before returning it.

thisFile <- function() {
  cmdArgs <- commandArgs(trailingOnly = FALSE)
  needle <- "--file="
  match <- grep(needle, cmdArgs)
  if (length(match) > 0) {
    # Rscript
    path <- cmdArgs[match]
    path <- gsub("\\~\\+\\~", " ", path)
    return(normalizePath(sub(needle, "", path)))
  } else {
    # 'source'd via R console
    return(normalizePath(sys.frames()[[1]]$ofile))
  }
}

Obviously you can still extend the else block like aprstar did.

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

How do I perform query filtering in django templates

For anyone looking for an answer in 2020. This worked for me.

In Views:

 class InstancesView(generic.ListView):
        model = AlarmInstance
        context_object_name = 'settings_context'
        queryset = Group.objects.all()
        template_name = 'insta_list.html'

        @register.filter
        def filter_unknown(self, aVal):
            result = aVal.filter(is_known=False)
            return result

        @register.filter
        def filter_known(self, aVal):
            result = aVal.filter(is_known=True)
            return result

In template:

{% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}

In pseudocode:

For each in model.child_object|view_filter:filter_arg

Hope that helps.

How to style components using makeStyles and still have lifecycle methods in Material UI?

Hi instead of using hook API, you should use Higher-order component API as mentioned here

I'll modify the example in the documentation to suit your need for class component

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

class HigherOrderComponentUsageExample extends React.Component {
  
  render(){
    const { classes } = this.props;
    return (
      <Button className={classes.root}>This component is passed to an HOC</Button>
      );
  }
}

HigherOrderComponentUsageExample.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponentUsageExample);

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

You can find the installed version of ur library from the properties inside references. For my case i had 8.0.0.0 installed. Error says Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies.

So i had to add the following manually inside web.config

  <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="6.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
      </dependentAssembly>

PDF Editing in PHP?

We use pdflib to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.

We use the commmercial version, but they also have a free/open source version which has some limitations.

Unfortunately, this only allows creation of PDF's.

If you want to open and 'edit' existing files, pdflib do provide a product which does this this, but costs a LOT

Java ArrayList clear() function

data.removeAll(data); will do the work, I think.

Json.NET serialize object with root name

Use anonymous class

Shape your model the way you want using anonymous classes:

var root = new 
{ 
    car = new 
    { 
        name = "Ford", 
        owner = "Henry"
    }
};

string json = JsonConvert.SerializeObject(root);

Install apps silently, with granted INSTALL_PACKAGES permission

Prerequisite:

Your APK needs to be signed by system as correctly pointed out earlier. One way to achieve that is building the AOSP image yourself and adding the source code into the build.

Code:

Once installed as a system app, you can use the package manager methods to install and uninstall an APK as following:

Install:

public boolean install(final String apkPath, final Context context) {
    Log.d(TAG, "Installing apk at " + apkPath);
    try {
        final Uri apkUri = Uri.fromFile(new File(apkPath));
        final String installerPackageName = "MyInstaller";
        context.getPackageManager().installPackage(apkUri, installObserver, PackageManager.INSTALL_REPLACE_EXISTING, installerPackageName);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

Uninstall:

public boolean uninstall(final String packageName, final Context context) {
    Log.d(TAG, "Uninstalling package " + packageName);
    try {
        context.getPackageManager().deletePackage(packageName, deleteObserver, PackageManager.DELETE_ALL_USERS);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

To have a callback once your APK is installed/uninstalled you can use this:

/**
 * Callback after a package was installed be it success or failure.
 */
private class InstallObserver implements IPackageInstallObserver {

    @Override
    public void packageInstalled(String packageName, int returnCode) throws RemoteException {

        if (packageName != null) {
            Log.d(TAG, "Successfully installed package " + packageName);
            callback.onAppInstalled(true, packageName);
        } else {
            Log.e(TAG, "Failed to install package.");
            callback.onAppInstalled(false, null);
        }
    }

    @Override
    public IBinder asBinder() {
        return null;
    }
}

/**
 * Callback after a package was deleted be it success or failure.
 */
private class DeleteObserver implements IPackageDeleteObserver {

    @Override
    public void packageDeleted(String packageName, int returnCode) throws RemoteException {
        if (packageName != null) {
            Log.d(TAG, "Successfully uninstalled package " + packageName);
            callback.onAppUninstalled(true, packageName);
        } else {
            Log.e(TAG, "Failed to uninstall package.");
            callback.onAppUninstalled(false, null);
        }
    }

    @Override
    public IBinder asBinder() {
        return null;
    }
}

/**
 * Callback to give the flow back to the calling class.
 */
public interface InstallerCallback {
    void onAppInstalled(final boolean success, final String packageName);
    void onAppUninstalled(final boolean success, final String packageName);
}

===> Tested on Android 8.1 and worked well.

Showing an image from console in Python

Why not just display it in the user's web browser?

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

Ship an application with a database

If the required data is not too large (limits I don´t know, would depend on a lot of things), you might also download the data (in XML, JSON, whatever) from a website/webapp. AFter receiving, execute the SQL statements using the received data creating your tables and inserting the data.

If your mobile app contains lots of data, it might be easier later on to update the data in the installed apps with more accurate data or changes.

How to open select file dialog via js?

In HTML only:

<label>
  <input type="file" name="input-name" style="display: none;" />
  <span>Select file</span>
</label>

Edit: I hadn't tested this in Blink, it actually doesn't work with a <button>, but it should work with most other elements–at least in recent browsers.

Check this fiddle with the code above.

Counter in foreach loop in C#

Not all collections have indexes. For instance, I can use a Dictionary with foreach (and iterate through all the keys and values), but I can't write get at individual elements using dictionary[0], dictionary[1] etc.

If I did want to iterate through a dictionary and keep track of an index, I'd have to use a separate variable that I incremented myself.

How can I tail a log file in Python?

Python is "batteries included" - it has a nice solution for it: https://pypi.python.org/pypi/pygtail

Reads log file lines that have not been read. Remembers where it finished last time, and continues from there.

import sys
from pygtail import Pygtail

for line in Pygtail("some.log"):
    sys.stdout.write(line)

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

Efficient way to return a std::vector in c++

In C++11, this is the preferred way:

std::vector<X> f();

That is, return by value.

With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

DOUBLE vs DECIMAL in MySQL

We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.

jwt check if token expired

verify itself returns an error if expired. Safer as @Gabriel said.

const jwt = require('jsonwebtoken')

router.use((req, res, next) => {
  const token = yourJwtService.getToken(req) // Get your token from the request
  jwt.verify(token, req.app.get('your-secret'), function(err, decoded) {
    if (err) throw new Error(err) // Manage different errors here (Expired, untrusted...)
    req.auth = decoded // If no error, token info is returned in 'decoded'
    next()
  });
})

And same written in async/await syntax:

const jwt = require('jsonwebtoken')
const jwtVerifyAsync = util.promisify(jwt.verify);

router.use(async (req, res, next) => {
  const token = yourJwtService.getToken(req) // Get your token from the request
  try {
    req.auth = await jwtVerifyAsync(token, req.app.get('your-secret')) // If no error, token info is returned
  } catch (err) {
    throw new Error(err) // Manage different errors here (Expired, untrusted...)
  }
  next()
});

How to check whether a given string is valid JSON in Java

It depends on what you are trying to prove with your validation. Certainly parsing the json as others have suggested is better than using regexes, because the grammar of json is more complicated than can be represented with just regexes.

If the json will only ever be parsed by your java code, then use the same parser to validate it.

But just parsing won't necessarily tell you if it will be accepted in other environments. e.g.

  • many parsers ignore trailing commas in an object or array, but old versions of IE can fail when they hit a trailing comma.
  • Other parsers may accept a trailing comma, but add an undefined/null entry after it.
  • Some parsers may allow unquoted property names.
  • Some parsers may react differently to non-ASCII characters in strings.

If your validation needs to be very thorough, you could:

Install a Python package into a different directory using pip?

Tested these options with python3.5 and pip 9.0.3:

pip install --target /myfolder [packages]

Installs ALL packages including dependencies under /myfolder. Does not take into account that dependent packages are already installed elsewhere in Python. You will find packages from /myfolder/[package_name]. In case you have multiple Python versions, this doesn't take that into account (no Python version in package folder name).

pip install --prefix /myfolder [packages]

Checks are dependencies already installed. Will install packages into /myfolder/lib/python3.5/site-packages/[packages]

pip install --root /myfolder [packages]

Checks dependencies like --prefix but install location will be /myfolder/usr/local/lib/python3.5/site-packages/[package_name].

pip install --user [packages]

Will install packages into $HOME: /home/[USER]/.local/lib/python3.5/site-packages Python searches automatically from this .local path so you don't need to put it to your PYTHONPATH.

=> In most of the cases --user is the best option to use. In case home folder can't be used because of some reason then --prefix.

Use jquery click to handle anchor onClick()

Lets take an anchor tag with an onclick event, that calls a Javascript function.

<a href="#" onClick="showDiv(1);">1</a>

Now in javascript write the below code

function showDiv(pageid)
{
   alert(pageid);
}

This will show you an alert of "1"....

Setting the MySQL root user password on OS X

Let us add this workaround that works on my laptop!

Mac with Osx Mojave 10.14.5

Mysql 8.0.17 was installed with homebrew

  • I run the following command to locate the path of mysql

    brew info mysql

  • Once the path is known, I run this :

    /usr/local/Cellar/mysql/8.0.17/bin/mysqld_safe --skip-grant-table

  • In another terminal I run :

    mysql -u root

  • Inside that terminal, I changed the root password using :

    update mysql.user set authentication_string='NewPassword' where user='root';

  • and to finish I run :

    FLUSH PRIVILEGES;

And voila the password was reset.

References :

How to install toolbox for MATLAB

There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license

http://www.mathworks.com/products/image/

There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.


If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.

How to set JAVA_HOME environment variable on Mac OS X 10.9?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

How to load image (and other assets) in Angular an project?

for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.

Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.

How to force IE to reload javascript?

If you are running ASP.Net, check out the Bundling and Minification module available in ASP.Net 4.5.

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

You can declare a "bundle" that points to your javascript file. Every time your file changes, it will generate a new querystring suffix... but will only do so when the file changes. This makes it super simple to deploy updates, because you don't even have to think about updating your tags with new version numbers.

It can also bundle multiple .js files together into one file, and minify them, all in one step. Ditto for css.

Asp.net Validation of viewstate MAC failed

<system.web>
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />
</system.web>

Creating your own header file in C

header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);


#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}

How to read json file into java with simple JSON library

Add Jackson databind:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.pr2</version>
</dependency>

Create DTO class with related fields and read JSON file:

ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);

What is The difference between ListBox and ListView

A ListView let you define a set of views for it and gives you a native way (WPF binding support) to control the display of ListView by using defined views.

Example:

XAML

<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
        <ListView.Resources>
            <GridView x:Key="one">
                <GridViewColumn Header="ID" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding id}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
            <GridView x:Key="two">                    
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.Resources>
        <ListView.Style>
            <Style TargetType="ListView">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ViewType}" Value="1">
                        <Setter Property="View" Value="{StaticResource one}" />
                    </DataTrigger>
                </Style.Triggers>
                <Setter Property="View" Value="{StaticResource two}" />
            </Style>
        </ListView.Style>  

Code Behind:

private int viewType;

public int ViewType
{
    get { return viewType; }
    set 
    { 
        viewType = value;
        UpdateProperty("ViewType");
    }
}        

private void listv_MouseEnter(object sender, MouseEventArgs e)
{
    ViewType = 1;
}

private void listv_MouseLeave(object sender, MouseEventArgs e)
{
    ViewType = 2;
}

OUTPUT:

Normal View: View 2 in above XAML

Normal

MouseOver View: View 1 in above XAML

Mouse Over

If you try to achieve above in a ListBox, probably you'll end up writing a lot more code forControlTempalate/ItemTemplate of ListBox.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

On Windows (msys) using Docker Toolbox/Machine, I had to add an extra / before /bin/bash to indicate that it was a *nix filepath.

So, docker run --rm -it <image>:latest //bin/bash

How to set $_GET variable

You can use GET variables in the action parameter of your form element. Example:

<form method="post" action="script.php?foo=bar">
    <input name="quu" ... />
    ...
</form>

This will give you foo as a GET variable and quu as a POST variable.

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Pandas: convert dtype 'object' to int

Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)

Linux find and grep command together

Now that the question is clearer, you can just do this in one

grep -R --include "*bills*" "put" .

With relevant flags

   -R, -r, --recursive
          Read  all  files  under  each  directory,  recursively;  this is
          equivalent to the -d recurse option.
   --include=GLOB
          Search only files whose base name matches GLOB  (using  wildcard
          matching as described under --exclude).

Android RatingBar change star colors

So I have been struggling with this issue for two hours and I have come up with a working solution for all API versions, where half stars ratings are also shown.

private void setRatingStarColor(Drawable drawable, @ColorInt int color)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        DrawableCompat.setTint(drawable, color);
    }
    else
    {
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
}

You call the method with this order of drawables:

    LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
    // Filled stars
    setRatingStarColor(stars.getDrawable(2), ContextCompat.getColor(getContext(), R.color.foreground));
    // Half filled stars
    setRatingStarColor(stars.getDrawable(1), ContextCompat.getColor(getContext(), R.color.background));
    // Empty stars
    setRatingStarColor(stars.getDrawable(0), ContextCompat.getColor(getContext(), R.color.background));

NOTE: Also you must specify attributes "max" and "numStars" in XML, otherwise half stars aren't shown.

How do I send a JSON string in a POST request in Go

In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)

So, in the end your code will become like follow:

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)
    request := gorequest.New()
    titleList := []string{"title1", "title2", "title3"}
    for _, title := range titleList {
        resp, body, errs := request.Post(url).
            Set("X-Custom-Header", "myvalue").
            Send(`{"title":"` + title + `"}`).
            End()
        if errs != nil {
            fmt.Println(errs)
            os.Exit(1)
        }
        fmt.Println("response Status:", resp.Status)
        fmt.Println("response Headers:", resp.Header)
        fmt.Println("response Body:", body)
    }
}

This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

ASP.NET MVC Razor render without encoding

HTML RAW :

@Html.Raw(yourString)

What is the Sign Off feature in Git for?

There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).

Headers or trailers (?1) like “sign-off” (?2) is, in current practice in projects like Git and Linux, effectively structured metadata for the commit. These are all appended to the end of the commit message, after the “free form” (unstructured) part of the body of the message. These are token–value (or key–value) pairs typically delimited by a colon and a space (:?).

Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:

 mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
 This is an ancient bug that was actually attempted to be fixed once
 (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
 get_user_pages() race for write access") but that was then undone due to
 problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").

 In the meantime, the s390 situation has long been fixed, and we can now
 fix it by checking the pte_dirty() bit properly (and do it better).  The
 s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
 software dirty bits") which made it into v3.9.  Earlier kernels will
 have to look at the page state itself.

 Also, the VM has become more scalable, and what used a purely
 theoretical race back then has become easier to trigger.

 To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
 we already did a COW" rather than play racy games with FOLL_WRITE that
 is very fundamental, and then use the pte dirty flag to validate that
 the FOLL_COW flag is still valid.

 Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
 Acked-by: Hugh Dickins <[email protected]>
 Reviewed-by: Michal Hocko <[email protected]>
 Cc: Andy Lutomirski <[email protected]>
 Cc: Kees Cook <[email protected]>
 Cc: Oleg Nesterov <[email protected]>
 Cc: Willy Tarreau <[email protected]>
 Cc: Nick Piggin <[email protected]>
 Cc: Greg Thelen <[email protected]>
 Cc: [email protected]
 Signed-off-by: Linus Torvalds <[email protected]>

In addition to the “sign-off” trailer in the above, there is:

  • “Cc” (was notified about the patch)
  • “Acked-by” (acknowledged by the owner of the code, “looks good to me”)
  • “Reviewed-by” (reviewed)
  • “Reported-and-tested-by” (reported and tested the issue (I assume))

Other projects, like for example Gerrit, have their own headers and associated meaning for them.

See: https://git.wiki.kernel.org/index.php/CommitMessageConventions

Moral of the story

It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.

[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.

How to push JSON object in to array using javascript

You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-

var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
    console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
    my_json = feed;
    console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
    data.push(my_json);
     //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
}); 
console.log(data);

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

Initialise numpy array of unknown length

Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

    a = []
    for x in y:
        a.append(x)
    a = np.array(a)

How to stop and restart memcached server?

if linux

if install by apt-get

service memcached stop
service memcached restart

if install by source code

Usage: /etc/init.d/memcached {start|stop|restart|force-reload|status}

can also simply kill $pid to stop

How to build PDF file from binary string returned from a web-service using javascript

Detect the browser and use Data-URI for Chrome and use PDF.js as below for other browsers.

PDFJS.getDocument(url_of_pdf)
.then(function(pdf) {
    return pdf.getPage(1);
})
.then(function(page) {
    // get a viewport
    var scale = 1.5;
    var viewport = page.getViewport(scale);
    // get or create a canvas
    var canvas = ...;
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    // render a page
    page.render({
        canvasContext: canvas.getContext('2d'),
        viewport: viewport
    });
})
.catch(function(err) {
    // deal with errors here!
});

Replace part of a string with another string

std::string has a replace method, is that what you are looking for?

You could try:

s.replace(s.find("$name"), sizeof("$name") - 1, "Somename");

I haven't tried myself, just read the documentation on find() and replace().

Getting first and last day of the current month

Try this code it is already built in c#

int lastDay = DateTime.DaysInMonth (2014, 2);

and the first day is always 1.

Good Luck!

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

Remove an item from array using UnderscoreJS

By Using underscore.js

var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

var resultArr = _.reject(arr,{id:3});

console.log(resultArr);

The result will be :: [{id:1name:'a'},{id:2,name:'c'}]

Get Image Height and Width as integer values?

Like this :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

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

I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

Can't change table design in SQL Server 2008

Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".

Java: int[] array vs int array[]

From JLS http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#10.2

Here are examples of declarations of array variables that do not create arrays:

int[ ] ai;          // array of int
short[ ][ ] as;         // array of array of short
Object[ ]   ao,     // array of Object
        otherAo;    // array of Object
Collection<?>[ ] ca;        // array of Collection of unknown type
short       s,      // scalar short 
        aas[ ][ ];  // array of array of short

Here are some examples of declarations of array variables that create array objects:

Exception ae[ ] = new Exception[3]; 
Object aao[ ][ ] = new Exception[2][3];
int[ ] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[ ] = { 'n', 'o', 't', ' ', 'a', ' ',
                 'S', 't', 'r', 'i', 'n', 'g' }; 
String[ ] aas = { "array", "of", "String", };

The [ ] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[ ] rowvector, colvector, matrix[ ];

This declaration is equivalent to:

byte rowvector[ ], colvector[ ], matrix[ ][ ];

Floating Div Over An Image

Actually just adding margin-bottom: -20px; to the tag class fixed it right up.

http://jsfiddle.net/dChUR/7/

Being block elements, div's naturally have defined borders that they try not to violate. To get them to layer for images, which have no content beside the image because they have no closing tag, you just have to force them to do what they do not want to do, like violate their natural boundaries.

.container {
  border: 1px solid #DDDDDD;
  width: 200px;
  height: 200px;
  }
.tag {
  float: left;
  position: relative;
  left: 0px;
  top: 0px;
  background-color: green;
  z-index: 1000;
  margin-bottom: -20px;
  }

Another toue to take would be to create div's using an image as the background, and then place content where ever you like.

<div id="imgContainer" style="
         background-image: url("foo.jpg"); 
         background-repeat: no-repeat; 
         background-size: cover; 
         -webkit-background-size: cover; 
         -mox-background-size: cover; 
         -o-background-size: cover;">
  <div id="theTag">BLAH BLAH BLAH</div>
</div>

console.log timestamps in Chrome?

I originally added this as a comment, but I wanted to add a screenshot as at least one person could not find the option (or maybe it was not available in their particular version for some reason).

On Chrome 68.0.3440.106 (and now checked in 72.0.3626.121) I had to

  • open dev tools (F12)
  • click the three-dot menu in the top right
  • click settings
  • select Preferences in the left menu
  • check show timestamps in the Console section of the settings screen

Settings > Preferences > Console > Show timestamps

Groovy String to Date

I think the best easy way in this case is to use parseToStringDate which is part of GDK (Groovy JDK enhancements):

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy containing US-locale-constants only (e.g. Sat for Saturdays). Such a string is generated by the toString method of Date

Example:

println(Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))

Adding an .env file to React Project

Webpack Users

If you are using webpack, you can install and use dotenv-webpack plugin, to do that follow steps below:

Install the package

yarn add dotenv-webpack

Create a .env file

// .env
API_KEY='my secret api key'

Add it to webpack.config.js file

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
  ...
  plugins: [
    new Dotenv()
  ]
  ...
};

Use it in your code as

process.env.API_KEY

For more information and configuration information, visit here

SQL select only rows with max value on a column

If you have many fields in select statement and you want latest value for all of those fields through optimized code:

select * from
(select * from table_name
order by id,rev desc) temp
group by id 

SQLAlchemy: how to filter date field?

from app import SQLAlchemyDB as db

Chance.query.filter(Chance.repo_id==repo_id, 
                    Chance.status=="1", 
                    db.func.date(Chance.apply_time)<=end, 
                    db.func.date(Chance.apply_time)>=start).count()

it is equal to:

select
   count(id)
from
   Chance
where
   repo_id=:repo_id 
   and status='1'
   and date(apple_time) <= end
   and date(apple_time) >= start

wish can help you.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Select the project -> Right-Click -> clean and build and then run the project again simply solve the problem for me.

As, multiple process could bind the same port for example port 8086, In that case I have to kill all the processes involved with the port with PID. That might be cumbersome.

Loop backwards using indices in Python?

Generally in Python, you can use negative indices to start from the back:

numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
    print numbers[-i - 1]

Result:

50
40
30
20
10

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

How (and why) to use display: table-cell (CSS)

The display:table family of CSS properties is mostly there so that HTML tables can be defined in terms of them. Because they're so intimately linked to a specific tag structure, they don't see much use beyond that.

If you were going to use these properties in your page, you would need a tag structure that closely mimicked that of tables, even though you weren't actually using the <table> family of tags. A minimal version would be a single container element (display:table), with direct children that can all be represented as rows (display:table-row), which themselves have direct children that can all be represented as cells (display:table-cell). There are other properties that let you mimic other tags in the table family, but they require analogous structures in the HTML. Without this, it's going to be very hard (if not impossible) to make good use of these properties.

MSSQL Error 'The underlying provider failed on Open'

I had the same issue few days ago, using "Integrated Security=True;" in the connection string you need to run the application pool identity under "localsystem" Sure this is not recommended but for testing it does the job.

This is how you can change the identity in IIS 7: http://www.iis.net/learn/manage/configuring-security/application-pool-identities

CSS Border Not Working

Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

C# Test if user has write access to a folder

You have a potential race condition in your code--what happens if the user has permissions to write to the folder when you check, but before the user actually writes to the folder this permission is withdrawn? The write will throw an exception which you will need to catch and handle. So the initial check is pointless. You might as well just do the write and handle any exceptions. This is the standard pattern for your situation.

How to set selectedIndex of select element using display text?

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

Bash array with spaces in elements

I agree with others that it's likely how you're accessing the elements that is the problem. Quoting the file names in the array assignment is correct:

FILES=(
  "2011-09-04 21.43.02.jpg"
  "2011-09-05 10.23.14.jpg"
  "2011-09-09 12.31.16.jpg"
  "2011-09-11 08.43.12.jpg"
)

for f in "${FILES[@]}"
do
  echo "$f"
done

Using double quotes around any array of the form "${FILES[@]}" splits the array into one word per array element. It doesn't do any word-splitting beyond that.

Using "${FILES[*]}" also has a special meaning, but it joins the array elements with the first character of $IFS, resulting in one word, which is probably not what you want.

Using a bare ${array[@]} or ${array[*]} subjects the result of that expansion to further word-splitting, so you'll end up with words split on spaces (and anything else in $IFS) instead of one word per array element.

Using a C-style for loop is also fine and avoids worrying about word-splitting if you're not clear on it:

for (( i = 0; i < ${#FILES[@]}; i++ ))
do
  echo "${FILES[$i]}"
done

How can I center a div within another div?

I have used the following method in a few projects:

https://jsfiddle.net/u3Ln0hm4/

.cellcenterparent{
  width: 100%;
  height: 100%;
  display: table;
}

.cellcentercontent{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

Image encryption/decryption using AES256 symmetric block ciphers

import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

class SecurityUtils {

  private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
      (byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };

  private static int BLOCKS = 128;

  public static byte[] encryptAES(String seed, String cleartext)
      throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes("UTF8"));
    SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    return cipher.doFinal(cleartext.getBytes("UTF8"));
  }

  public static byte[] decryptAES(String seed, byte[] data) throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes("UTF8"));
    SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    return cipher.doFinal(data);
  }

  private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(BLOCKS, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
  }

  private static byte[] pad(byte[] seed) {
    byte[] nseed = new byte[BLOCKS / 8];
    for (int i = 0; i < BLOCKS / 8; i++)
      nseed[i] = 0;
    for (int i = 0; i < seed.length; i++)
      nseed[i] = seed[i];

    return nseed;
  }

  public static byte[] encryptPBE(String password, String cleartext)
      throws Exception {
    SecretKeyFactory factory = SecretKeyFactory
        .getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    return cipher.doFinal(cleartext.getBytes("UTF-8"));
  }

  public static String decryptPBE(SecretKey secret, String ciphertext,
      byte[] iv) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
    return new String(cipher.doFinal(ciphertext.getBytes()), "UTF-8");
  }

}

Android OnClickListener - identify a button

Another way of doing it is a single listener from activity , like this:

public class MyActivity extends Activity implements OnClickListener {
    .......  code

    //my listener
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mybutton) { 
            DoSomething();
            return;
        }

        if (v.getId() == R.id.mybutton2) { 
            DoSomething2();
            return;
        }
    }
}

I Like to do it with single IF instead of switch-else, but if you prefer that, then you should do:

//my listener
@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.mybutton:
        { 
             DoSomething();
             break;
        }

        case R.id.mybutton2:
        {
            DoSomething();
            break;
        }
    }
}

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

It's because you can't resolve the host name Maybe DNS problems, host is unreachable...

try to use IP address instead of host name... ping this host name... nslookup it...

Script to Change Row Color when a cell changes text

I used GENEGC's script, but I found it quite slow.

It is slow because it scans whole sheet on every edit.

So I wrote way faster and cleaner method for myself and I wanted to share it.

function onEdit(e) {
    if (e) { 
        var ss = e.source.getActiveSheet();
        var r = e.source.getActiveRange(); 

        // If you want to be specific
        // do not work in first row
        // do not work in other sheets except "MySheet"
        if (r.getRow() != 1 && ss.getName() == "MySheet") {

            // E.g. status column is 2nd (B)
            status = ss.getRange(r.getRow(), 2).getValue();

            // Specify the range with which You want to highlight
            // with some reading of API you can easily modify the range selection properties
            // (e.g. to automatically select all columns)
            rowRange = ss.getRange(r.getRow(),1,1,19);

            // This changes font color
            if (status == 'YES') {
                rowRange.setFontColor("#999999");
            } else if (status == 'N/A') {
                rowRange.setFontColor("#999999");
            // DEFAULT
            } else if (status == '') { 
                rowRange.setFontColor("#000000");
            }   
        }
    }
}

Converting integer to string in Python

For someone who wants to convert int to string in specific digits, the below method is recommended.

month = "{0:04d}".format(localtime[1])

For more details, you can refer to Stack Overflow question Display number with leading zeros.

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

What's the difference between nohup and ampersand

The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.

deleted object would be re-saved by cascade (remove deleted object from associations)

I had the same exception, caused when attempting to remove the kid from the person (Person - OneToMany - Kid). On Person side annotation:

@OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, ... cascade    = CascadeType.ALL)
public Set<Kid> getKids() {    return kids; }

On Kid side annotation:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "person_id")
public Person getPerson() {        return person;    }

So solution was to remove cascade = CascadeType.ALL, just simple: @ManyToOne on the Kid class and it started to work as expected.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

What is correct media query for IPad Pro?

I tried several of the proposed answers but the problem is that the media queries conflicted with other queries and instead of displaying the mobile CSS on the iPad Pro, it was displaying the desktop CSS. So instead of using max and min for dimensions, I used the EXACT VALUES and it works because on the iPad pro you can't resize the browser.

Note that I added a query for mobile CSS that I use for devices with less than 900px width; feel free to remove it if needed.

This is the query, it combines both landscape and portrait, it works for the 12.9" and if you need to target the 10.5" you can simply add the queries for these dimensions:

@media only screen and (max-width: 900px), 
(height: 1024px) and (width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: landscape), 
(width: 1024px) and (height: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: portrait)  {

     // insert mobile and iPad Pro 12.9" CSS here    
}

How to find the index of an element in an array in Java?

Alternatively, you can use Commons Lang ArrayUtils class:

int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);

There are overloaded variants of indexOf() method for different array types.

Multiline strings in VB.NET

Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:

 s="""this is gonna 
last quite a 
few lines"""

then do a:

  for i in s.split('\n'):
    print 'mySB.AppendLine("%s")' % i

#    mySB.AppendLine("this is gonna")
#    mySB.AppendLine("last quite a")
#    mySB.AppendLine("few lines")

or

  print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))

#    "this is gonna" & _ 
#    "last quite a" & _ 
#    "few lines"

then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey (fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.

How to send 500 Internal Server Error error from a PHP script

You can simplify it like this:

if ( that_happened || something_else_happened )
{
    header('X-Error-Message: Incorrect username or password', true, 500);
    die;
}

It will return following header:

HTTP/1.1 500 Internal Server Error
...
X-Error-Message: Incorrect username or password
...

Added: If you need to know exactly what went wrong, do something like this:

if ( that_happened )
{
    header('X-Error-Message: Incorrect username', true, 500);
    die('Incorrect username');
}

if ( something_else_happened )
{
    header('X-Error-Message: Incorrect password', true, 500);
    die('Incorrect password');
}

TypeError: method() takes 1 positional argument but 2 were given

Something else to consider when this type of error is encountered:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__() where there was object inheritance.

The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).

Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.

In the case of the sytax error: The fix is simple, just edit the custom init statement:

def __init__(self, name):
    self.name = name

What should I do when 'svn cleanup' fails?

Run svn cleanup command in a terminal (if it fails from Eclipse which was my case):

~/path/to/svn-folder/$ svn cleanup

I tried different solutions explained here, but none worked.

Action Team ? Update to head fails:

svn: E155004: There are unfinished work items in '/home/user/path/to/svn-folder'; run 'svn cleanup' first.

Action Team ? Cleanup fails with same error.

Solution that worked for me: run svn cleanup command in a terminal.

The command succeeded.

Then Team ? Update in Eclipse worked again.

Note: my SVN version is 1.9.3.

Also check Chris's answer if svn cleanup does not work.

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

Using a scanner to accept String input and storing in a String Array

One of the problem with this code is here :

name += contactName[];

This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.

Instead use this:

contactName[index] = name;

this instruction will store the variable name in the contactName array at the index index.

The second problem you have is that you don't have the variable index.

What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)

Adding a month to a date in T SQL

select * from Reference where reference_dt = DATEADD(mm, 1, reference_dt)

Send email using the GMail SMTP server from a PHP page

Gmail requires port 465, and also it's the code from phpmailer :)

How to send email from SQL Server?

To send mail through SQL Server we need to set up DB mail profile we can either use T-SQl or SQL Database mail option in sql server to create profile. After below code is used to send mail through query or stored procedure.

Use below link to create DB mail profile

http://www.freshcodehub.com/Article/42/configure-database-mail-in-sql-server-database

http://www.freshcodehub.com/Article/43/create-a-database-mail-configuration-using-t-sql-script

_x000D_
_x000D_
--Sending Test Mail_x000D_
EXEC msdb.dbo.sp_send_dbmail_x000D_
@profile_name = 'TestProfile', _x000D_
@recipients = 'To Email Here', _x000D_
@copy_recipients ='CC Email Here',             --For CC Email if exists_x000D_
@blind_copy_recipients= 'BCC Email Here',      --For BCC Email if exists_x000D_
@subject = 'Mail Subject Here', _x000D_
@body = 'Mail Body Here',_x000D_
@body_format='HTML',_x000D_
@importance ='HIGH',_x000D_
@file_attachments='C:\Test.pdf';               --For Attachments if exists
_x000D_
_x000D_
_x000D_

Efficiently sorting a numpy array in descending order?

Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

Hope it helps you out!

I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

MVC - Set selected value of SelectList

Why are you trying to set the value after you create the list? My guess is you are creating the list in your model instead of in your view. I recommend creating the underlying enumerable in your model and then using this to build the actual SelectList:

<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %>

That way your selected value is always set just as the view is rendered and not before. Also, you don't have to put any unnecessary UI classes (i.e. SelectList) in your model and it can remain unaware of the UI.

Can I have multiple primary keys in a single table?

A Table can have a Composite Primary Key which is a primary key made from two or more columns. For example:

CREATE TABLE userdata (
  userid INT,
  userdataid INT,
  info char(200),
  primary key (userid, userdataid)
);

Update: Here is a link with a more detailed description of composite primary keys.

BeanFactory vs ApplicationContext

To me, the primary difference to choose BeanFactory over ApplicationContext seems to be that ApplicationContext will pre-instantiate all of the beans. From the Spring docs:

Spring sets properties and resolves dependencies as late as possible, when the bean is actually created. This means that a Spring container which has loaded correctly can later generate an exception when you request an object if there is a problem creating that object or one of its dependencies. For example, the bean throws an exception as a result of a missing or invalid property. This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost of some upfront time and memory to create these beans before they are actually needed, you discover configuration issues when the ApplicationContext is created, not later. You can still override this default behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.

Given this, I initially chose BeanFactory for use in integration/performance tests since I didn't want to load the entire application for testing isolated beans. However -- and somebody correct me if I'm wrong -- BeanFactory doesn't support classpath XML configuration. So BeanFactory and ApplicationContext each provide a crucial feature I wanted, but neither did both.

Near as I can tell, the note in the documentation about overriding default instantiation behavior takes place in the configuration, and it's per-bean, so I can't just set the "lazy-init" attribute in the XML file or I'm stuck maintaining a version of it for test and one for deployment.

What I ended up doing was extending ClassPathXmlApplicationContext to lazily load beans for use in tests like so:

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

    public LazyLoadingXmlApplicationContext(String[] configLocations) {
        super(configLocations);
    }

    /**
     * Upon loading bean definitions, force beans to be lazy-initialized.
     * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
     */

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
        super.loadBeanDefinitions(reader);
        for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);
            beanDefinition.setLazyInit(true);
        }
    }

}

Include PHP file into HTML file

Create a .htaccess file in directory and add this code to .htaccess file

AddHandler x-httpd-php .html .htm

or

AddType application/x-httpd-php .html .htm

It will force Apache server to parse HTML or HTM files as PHP Script

How to make connection to Postgres via Node.js

Slonik is an alternative to answers proposed by Kuberchaun and Vitaly.

Slonik implements safe connection handling; you create a connection pool and connection opening/handling is handled for you.

import {
  createPool,
  sql
} from 'slonik';

const pool = createPool('postgres://user:password@host:port/database');

return pool.connect((connection) => {
  // You are now connected to the database.
  return connection.query(sql`SELECT foo()`);
})
  .then(() => {
    // You are no longer connected to the database.
  });

postgres://user:password@host:port/database is your connection string (or more canonically a connection URI or DSN).

The benefit of this approach is that your script ensures that you never accidentally leave hanging connections.

Other benefits for using Slonik include:

Bootstrap modal not displaying

After encountering this I was surprised to find that none of these solutions worked, as it seems fairly straight forward and I had similar markup working on a different page.

With my configuration, I had existing jQuery code bound to the same selector triggering the modal. Once starting the process of elimination, all I had to do was comment/remove e.stopPropagation() within my existing script.

Filtering Sharepoint Lists on a "Now" or "Today"

Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

Try this:

  1. git push -u origin master
  2. git push -f origin master

Sometimes #1 works and sometimes #2 for me. I am not sure why it reacts in this way

How to skip the OPTIONS preflight request?

setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation

$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);

Error - is not marked as serializable

If you store an object in session state, that object must be serializable.

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/asp_dotnet_bad_practices_non_serializable_object_stored_in_session.html


edit:

In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.

https://vulncat.hpefod.com/en/detail?id=desc.structural.dotnet.asp_dotnet_bad_practices_non_serializable_object_stored_in_session#C%23%2fVB.NET%2fASP.NET

jQuery deferreds and promises - .then() vs .done()

There is a very simple mental mapping in response that was a bit hard to find in the other answers:

Find nearest latitude/longitude with an SQL query

It sounds like you want to do a nearest neighbour search with some bound on the distance. SQL does not support anything like this as far as I am aware and you would need to use an alternative data structure such as an R-tree or kd-tree.

Python error: "IndexError: string index out of range"

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

so_far = " " * len(word)

?

Edit:

try something like

print "%d / %d" % (new, so_far)

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

Sorting options elements alphabetically using jQuery

I know this topic is old but I think my answer can be useful for a lot of people.

Here is jQuery plugin made from Pointy's answer using ES6:

/**
 * Sort values alphabetically in select
 * source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
 */
$.fn.extend({
    sortSelect() {
        let options = this.find("option"),
            arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();

        arr.sort((o1, o2) => { // sort select
            let t1 = o1.t.toLowerCase(), 
                t2 = o2.t.toLowerCase();
            return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
        });

        options.each((i, o) => {
            o.value = arr[i].v;
            $(o).text(arr[i].t);
        });
    }
});

Use is very easy

$("select").sortSelect();

How do I rotate a picture in WinForms

This is an old thread, and there are several other threads about C# WinForms image rotation, but now that I've come up with my solution I figure this is as good a place to post it as any.

  /// <summary>
  /// Method to rotate an Image object. The result can be one of three cases:
  /// - upsizeOk = true: output image will be larger than the input, and no clipping occurs 
  /// - upsizeOk = false & clipOk = true: output same size as input, clipping occurs
  /// - upsizeOk = false & clipOk = false: output same size as input, image reduced, no clipping
  /// 
  /// A background color must be specified, and this color will fill the edges that are not 
  /// occupied by the rotated image. If color = transparent the output image will be 32-bit, 
  /// otherwise the output image will be 24-bit.
  /// 
  /// Note that this method always returns a new Bitmap object, even if rotation is zero - in 
  /// which case the returned object is a clone of the input object. 
  /// </summary>
  /// <param name="inputImage">input Image object, is not modified</param>
  /// <param name="angleDegrees">angle of rotation, in degrees</param>
  /// <param name="upsizeOk">see comments above</param>
  /// <param name="clipOk">see comments above, not used if upsizeOk = true</param>
  /// <param name="backgroundColor">color to fill exposed parts of the background</param>
  /// <returns>new Bitmap object, may be larger than input image</returns>
  public static Bitmap RotateImage(Image inputImage, float angleDegrees, bool upsizeOk, 
                                   bool clipOk, Color backgroundColor)
  {
     // Test for zero rotation and return a clone of the input image
     if (angleDegrees == 0f)
        return (Bitmap)inputImage.Clone();

     // Set up old and new image dimensions, assuming upsizing not wanted and clipping OK
     int oldWidth = inputImage.Width;
     int oldHeight = inputImage.Height;
     int newWidth = oldWidth;
     int newHeight = oldHeight;
     float scaleFactor = 1f;

     // If upsizing wanted or clipping not OK calculate the size of the resulting bitmap
     if (upsizeOk || !clipOk)
     {
        double angleRadians = angleDegrees * Math.PI / 180d;

        double cos = Math.Abs(Math.Cos(angleRadians));
        double sin = Math.Abs(Math.Sin(angleRadians));
        newWidth = (int)Math.Round(oldWidth * cos + oldHeight * sin);
        newHeight = (int)Math.Round(oldWidth * sin + oldHeight * cos);
     }

     // If upsizing not wanted and clipping not OK need a scaling factor
     if (!upsizeOk && !clipOk)
     {
        scaleFactor = Math.Min((float)oldWidth / newWidth, (float)oldHeight / newHeight);
        newWidth = oldWidth;
        newHeight = oldHeight;
     }

     // Create the new bitmap object. If background color is transparent it must be 32-bit, 
     //  otherwise 24-bit is good enough.
     Bitmap newBitmap = new Bitmap(newWidth, newHeight, backgroundColor == Color.Transparent ? 
                                      PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb);
     newBitmap.SetResolution(inputImage.HorizontalResolution, inputImage.VerticalResolution);

     // Create the Graphics object that does the work
     using (Graphics graphicsObject = Graphics.FromImage(newBitmap))
     {
        graphicsObject.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsObject.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphicsObject.SmoothingMode = SmoothingMode.HighQuality;

        // Fill in the specified background color if necessary
        if (backgroundColor != Color.Transparent)
           graphicsObject.Clear(backgroundColor);

        // Set up the built-in transformation matrix to do the rotation and maybe scaling
        graphicsObject.TranslateTransform(newWidth / 2f, newHeight / 2f);

        if (scaleFactor != 1f)
           graphicsObject.ScaleTransform(scaleFactor, scaleFactor);

        graphicsObject.RotateTransform(angleDegrees);
        graphicsObject.TranslateTransform(-oldWidth / 2f, -oldHeight / 2f);

        // Draw the result 
        graphicsObject.DrawImage(inputImage, 0, 0);
     }

     return newBitmap;
  }

This is the result of many sources of inspiration, here at StackOverflow and elsewhere. Naveen's answer on this thread was especially helpful.

Failed to Connect to MySQL at localhost:3306 with user root

  1. go to apple icon on the top left corn and click "System Preference"

  2. find "Mysql" at the bottom and click it

  3. "start Mysql server"

How to read a text file in project's root directory?

In this code you access to root directory project:

 string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

then:

StreamReader r = new StreamReader(_filePath + "/cities2.json"))

How to Validate Google reCaptcha on Form Submit

You can verify the response in 3 ways as per the Google reCAPTCHA documentation:

  1. g-recaptcha-response: Once user checks the checkbox (I am not a robot), a field with id g-recaptcha-response gets populated in your HTML.
    You can now use the value of this field to know if the user is a bot or not, using the below mentioed lines:-

    var captchResponse = $('#g-recaptcha-response').val();
    if(captchResponse.length == 0 )
        //user has not yet checked the 'I am not a robot' checkbox
    else 
        //user is a verified human and you are good to submit your form now
    
  2. Before you are about to submit your form, you can make a call as follows:-

    var isCaptchaValidated = false;
    var response = grecaptcha.getResponse();
    if(response.length == 0) {
        isCaptchaValidated = false;
        toast('Please verify that you are a Human.');
    } else {
        isCaptchaValidated = true;
    }
    
    
    if (isCaptchaValidated ) {
        //you can now submit your form
    }
    
  3. You can display your reCAPTCHA as follows:-

    <div class="col s12 g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback='doSomething'></div>
    

    And then define the function in your JavaScript, which can also be used to submit your form.

    function doSomething() { alert(1); }
    

    Now, once the checkbox (I am not a robot) is checked, you will get a callback to the defined callback, which is doSomething in your case.

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

Creating dummy variables in pandas for python

When I think of dummy variables I think of using them in the context of OLS regression, and I would do something like this:

import numpy as np
import pandas as pd
import statsmodels.api as sm

my_data = np.array([[5, 'a', 1],
                    [3, 'b', 3],
                    [1, 'b', 2],
                    [3, 'a', 1],
                    [4, 'b', 2],
                    [7, 'c', 1],
                    [7, 'c', 1]])                


df = pd.DataFrame(data=my_data, columns=['y', 'dummy', 'x'])
just_dummies = pd.get_dummies(df['dummy'])

step_1 = pd.concat([df, just_dummies], axis=1)      
step_1.drop(['dummy', 'c'], inplace=True, axis=1)
# to run the regression we want to get rid of the strings 'a', 'b', 'c' (obviously)
# and we want to get rid of one dummy variable to avoid the dummy variable trap
# arbitrarily chose "c", coefficients on "a" an "b" would show effect of "a" and "b"
# relative to "c"
step_1 = step_1.applymap(np.int) 

result = sm.OLS(step_1['y'], sm.add_constant(step_1[['x', 'a', 'b']])).fit()
print result.summary()

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

It sounds like your ~/.ssh/authorized_keys file is not set up correctly. Verify that:

  • It is in the correct path.
  • The permissions of the file are 0600.
  • The permissions of ~/.ssh are 0700.

force Maven to copy dependencies into target/lib

Take a look at the Maven dependency plugin, specifically, the dependency:copy-dependencies goal. Take a look at the example under the heading The dependency:copy-dependencies mojo. Set the outputDirectory configuration property to ${basedir}/target/lib (I believe, you'll have to test).

Hope this helps.

How to stop "setInterval"

Store the return of setInterval in a variable, and use it later to clear the interval.

var timer = null;
$("textarea").blur(function(){
    timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
    if(timer){
       window.clearInterval(timer);
       timer = null
    }
});

__FILE__, __LINE__, and __FUNCTION__ usage in C++

FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.

PS:

static string  getScopedClassMethod( string thePrettyFunction )
{
  size_t index = thePrettyFunction . find( "(" );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( index );

  index = thePrettyFunction . rfind( " " );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( 0, index + 1 );

  return thePrettyFunction;   /* The scoped class name. */
}

How to split a string of space separated numbers into integers?

l = (int(x) for x in s.split())

If you are sure there are always two integers you could also do:

a,b = (int(x) for x in s.split())

or if you plan on modifying the array after

l = [int(x) for x in s.split()]

Change arrow colors in Bootstraps carousel

This worked for me:

.carousel-control-prev-icon {
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23000' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e");
      }
      
      .carousel-control-next-icon {
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23000' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5L3.75 4l-2.5 2.5L2.75 8l4-4-4-4z'/%3e%3c/svg%3e");
      }

I changed the color in the url of the icon. Thats the original that is used in the bootstrap page but with this section in black:

"...fill='%23000'..."

How to search for an element in a golang slice

As other guys commented before you can write your own procedure with anonymous function to solve this issue.

I used two ways to solve it:

func Find(slice interface{}, f func(value interface{}) bool) int {
    s := reflect.ValueOf(slice)
    if s.Kind() == reflect.Slice {
        for index := 0; index < s.Len(); index++ {
            if f(s.Index(index).Interface()) {
                return index
            }
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 12,
    }) 
    
    idx := Find(destinationList, func(value interface{}) bool {
        return value.(UserInfo).UserId == userId
    })
    
    if idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

Second method with less computational cost:

func Search(length int, f func(index int) bool) int {
    for index := 0; index < length; index++ {
        if f(index) {
            return index
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 123,
    }) 
    
    idx := Search(len(destinationList), func(index int) bool {
        return destinationList[index].UserId == userId
    })
    
    if  idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

How can I temporarily disable a foreign key constraint in MySQL?

It's not a good idea to set a foreign key constraint to 0, because if you do, your database would not ensure it is not violating referential integrity. This could lead to inaccurate, misleading, or incomplete data.

You make a foreign key for a reason: because all the values in the child column shall be the same as a value in the parent column. If there are no foreign key constraints, a child row can have a value that is not in the parent row, which would lead to inaccurate data.

For instance, let's say you have a website for students to login and every student must register for an account as a user. You have one table for user ids, with user id as a primary key; and another table for student accounts, with student id as a column. Since every student must have a user id, it would make sense to make the student id from the student accounts table a foreign key that references the primary key user id in the user ids table. If there are no foreign key checks, a student could end up having a student id and no user id, which means a student can get an account without being a user, which is wrong.

Imagine if it happens to a large amount of data. That's why you need the foreign key check.

It's best to figure out what is causing the error. Most likely, you are trying to delete from a parent row without deleting from a child row. Try deleting from the child row before deleting from the parent row.

What is the difference between 'typedef' and 'using' in C++11?

They are essentially the same but using provides alias templates which is quite useful. One good example I could find is as follows:

namespace std {
 template<typename T> using add_const_t = typename add_const<T>::type;
}

So, we can use std::add_const_t<T> instead of typename std::add_const<T>::type

MySQL Event Scheduler on a specific time everyday

CREATE EVENT test_event_03
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
   INSERT INTO messages(message,created_at)
   VALUES('Test MySQL recurring Event',NOW());

Equivalent of LIMIT and OFFSET for SQL Server?

Another sample :

declare @limit int 
declare @offset int 
set @offset = 2;
set @limit = 20;
declare @count int
declare @idxini int 
declare @idxfim int 
select @idxfim = @offset * @limit
select @idxini = @idxfim - (@limit-1);
WITH paging AS
    (
        SELECT 
             ROW_NUMBER() OVER (order by object_id) AS rowid, *
        FROM 
            sys.objects 
    )
select *
    from 
        (select COUNT(1) as rowqtd from paging) qtd, 
            paging 
    where 
        rowid between @idxini and @idxfim
    order by 
        rowid;

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

I am a beginner in Maven - don't know much about it. Carefully check on your input i.e. file path in my case. After I have carefully check, my file path is wrong so it leads to this error. After I fixed it, it works magically lol.

Auto-increment primary key in SQL tables

I think there is a way to do it at definition stage like this

create table employee( id int identity, name varchar(50), primary key(id) ).. I am trying to see if there is a way to alter an existing table and make the column as Identity which does not look possible theoretically (as the existing values might need modification)

Keep overflow div scrolled to bottom unless user scrolls up

I was able to get this working with CSS only.

The trick is to use display: flex; and flex-direction: column-reverse;

The browser treats the bottom like its the top. Assuming the browsers you're targeting support flex-box, the only caveat is that the markup has to be in reverse order.

Here is a working example. https://codepen.io/jimbol/pen/YVJzBg

What is the difference between . (dot) and $ (dollar sign)?

One application that is useful and took me some time to figure out from the very short description at learn you a haskell: Since:

f $ x = f x

and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4+) analogous to (++", world") "hello".

Why would anyone do this? For lists of functions, for example. Both:

map (++", world") ["hello","goodbye"]`

and:

map ($ 3) [(4+),(3*)]

are shorter than map (\x -> x ++ ", world") ... or map (\f -> f 3) .... Obviously, the latter variants would be more readable for most people.

How do I get into a non-password protected Java keystore or change the password?

Mac Mountain Lion has the same password now it uses Oracle.

Get IP address of an interface on Linux

If you don't mind the binary size, you can use iproute2 as library.

iproute2-as-lib

Pros:

  • No need to write the socket layer code.
  • More or even more information about network interfaces can be got. Same functionality with the iproute2 tools.
  • Simple API interface.

Cons:

  • iproute2-as-lib library size is big. ~500kb.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

Instead of using Ajax Post method, you can use dynamic form along with element. It will works even page is loaded in SSL and submitted source is non SSL.

You need to set value value of element of form.

Actually new dynamic form will open as non SSL mode in separate tab of Browser when target attribute has set '_blank'

var f = document.createElement('form');
f.action='http://XX.XXX.XX.XX/vicidial/non_agent_api.php';
f.method='POST';
//f.target='_blank';
//f.enctype="multipart/form-data"

var k=document.createElement('input');
k.type='hidden';k.name='CustomerID';
k.value='7299';
f.appendChild(k);



//var z=document.getElementById("FileNameId")
//z.setAttribute("name", "IDProof");
//z.setAttribute("id", "IDProof");
//f.appendChild(z);

document.body.appendChild(f);
f.submit()

What's the difference between lists and tuples?

Just a quick extension to list vs tuple responses:

  • Due to dynamic nature, list allocates more bit buckets than the actual memory required. This is done to prevent costly reallocation operation in case extra items are appended in the future.

  • On the other hand, being static, lightweight tuple object does not reserve extra memory required to store them.

Android background music service

way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer

How to get Current Directory?

IMHO here are some improvements to anon's answer.

#include <windows.h>
#include <string>
#include <iostream>

std::string GetExeFileName()
{
  char buffer[MAX_PATH];
  GetModuleFileName( NULL, buffer, MAX_PATH );
  return std::string(buffer);
}

std::string GetExePath() 
{
  std::string f = GetExeFileName();
  return f.substr(0, f.find_last_of( "\\/" ));
}