Programs & Examples On #Ironscheme

IronScheme is a R6RS Scheme implementation in .NET.

Reading settings from app.config or web.config in .NET

I had the same problem. Just read them this way: System.Configuration.ConfigurationSettings.AppSettings["MySetting"]

How do I change the default application icon in Java?

Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.

com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );

That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.

How to save and extract session data in codeigniter

First you have load session library.

$this->load->library("session");

You can load it in auto load, which I think is better.

To set session

$this->session->set_userdata("SESSION_NAME","VALUE");

To extract Data

$this->session->userdata("SESSION_NAME");

rawQuery(query, selectionArgs)

see below code it may help you.

String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);

or

String q = "SELECT * FROM customer WHERE _id = " + customerDbId  ;
Cursor mCursor = mDb.rawQuery(q, null);

Could not connect to React Native development server on Android

This is most probably a firewall issue. If someone using ubuntu faces this issue , then you can use

sudo service iptables stop

to disable the firewall for the port to be accessible

Best way to script remote SSH commands in Batch (Windows)

You can also use Bash on Ubuntu on Windows directly. E.g.,

bash -c "ssh -t user@computer 'cd /; sudo my-command'"

Per Martin Prikryl's comment below:

The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

Regex pattern including all special characters

If you only rely on ASCII characters, you can rely on using the hex ranges on the ASCII table. Here is a regex that will grab all special characters in the range of 33-47, 58-64, 91-96, 123-126

[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]

However you can think of special characters as not normal characters. If we take that approach, you can simply do this

^[A-Za-z0-9\s]+

Hower this will not catch _ ^ and probably others.

How do I close an open port from the terminal on the Mac?

  1. Find out the process ID (PID) which is occupying the port number (e.g., 5955) you would like to free

    sudo lsof -i :5955
    
  2. Kill the process which is currently using the port using its PID

    sudo kill -9 PID
    

UTF-8 encoding problem in Spring MVC

There are some similar questions: Spring MVC response encoding issue, Custom HttpMessageConverter with @ResponseBody to do Json things.

However, my simple solution:

@RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public ModelAndView getMyList(){
  String test = "ccždš";
  ...
  ModelAndView mav = new ModelAndView("html_utf8");
  mav.addObject("responseBody", test);
}

and the view html_utf8.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>${responseBody}

No additional classes and configuration.
And You can also create another view (for example json_utf8) for other content type.

Use of PUT vs PATCH methods in REST API real life scenarios

NOTE: When I first spent time reading about REST, idempotence was a confusing concept to try to get right. I still didn't get it quite right in my original answer, as further comments (and Jason Hoetger's answer) have shown. For a while, I have resisted updating this answer extensively, to avoid effectively plagiarizing Jason, but I'm editing it now because, well, I was asked to (in the comments).

After reading my answer, I suggest you also read Jason Hoetger's excellent answer to this question, and I will try to make my answer better without simply stealing from Jason.

Why is PUT idempotent?

As you noted in your RFC 2616 citation, PUT is considered idempotent. When you PUT a resource, these two assumptions are in play:

  1. You are referring to an entity, not to a collection.

  2. The entity you are supplying is complete (the entire entity).

Let's look at one of your examples.

{ "username": "skwee357", "email": "[email protected]" }

If you POST this document to /users, as you suggest, then you might get back an entity such as

## /users/1

{
    "username": "skwee357",
    "email": "[email protected]"
}

If you want to modify this entity later, you choose between PUT and PATCH. A PUT might look like this:

PUT /users/1
{
    "username": "skwee357",
    "email": "[email protected]"       // new email address
}

You can accomplish the same using PATCH. That might look like this:

PATCH /users/1
{
    "email": "[email protected]"       // new email address
}

You'll notice a difference right away between these two. The PUT included all of the parameters on this user, but PATCH only included the one that was being modified (email).

When using PUT, it is assumed that you are sending the complete entity, and that complete entity replaces any existing entity at that URI. In the above example, the PUT and PATCH accomplish the same goal: they both change this user's email address. But PUT handles it by replacing the entire entity, while PATCH only updates the fields that were supplied, leaving the others alone.

Since PUT requests include the entire entity, if you issue the same request repeatedly, it should always have the same outcome (the data you sent is now the entire data of the entity). Therefore PUT is idempotent.

Using PUT wrong

What happens if you use the above PATCH data in a PUT request?

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"
}
PUT /users/1
{
    "email": "[email protected]"       // new email address
}

GET /users/1
{
    "email": "[email protected]"      // new email address... and nothing else!
}

(I'm assuming for the purposes of this question that the server doesn't have any specific required fields, and would allow this to happen... that may not be the case in reality.)

Since we used PUT, but only supplied email, now that's the only thing in this entity. This has resulted in data loss.

This example is here for illustrative purposes -- don't ever actually do this. This PUT request is technically idempotent, but that doesn't mean it isn't a terrible, broken idea.

How can PATCH be idempotent?

In the above example, PATCH was idempotent. You made a change, but if you made the same change again and again, it would always give back the same result: you changed the email address to the new value.

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"
}
PATCH /users/1
{
    "email": "[email protected]"       // new email address
}

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"       // email address was changed
}
PATCH /users/1
{
    "email": "[email protected]"       // new email address... again
}

GET /users/1
{
    "username": "skwee357",
    "email": "[email protected]"       // nothing changed since last GET
}

My original example, fixed for accuracy

I originally had examples that I thought were showing non-idempotency, but they were misleading / incorrect. I am going to keep the examples, but use them to illustrate a different thing: that multiple PATCH documents against the same entity, modifying different attributes, do not make the PATCHes non-idempotent.

Let's say that at some past time, a user was added. This is the state that you are starting from.

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "10001"
}

After a PATCH, you have a modified entity:

PATCH /users/1
{"email": "[email protected]"}

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",    // the email changed, yay!
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "10001"
}

If you then repeatedly apply your PATCH, you will continue to get the same result: the email was changed to the new value. A goes in, A comes out, therefore this is idempotent.

An hour later, after you have gone to make some coffee and take a break, someone else comes along with their own PATCH. It seems the Post Office has been making some changes.

PATCH /users/1
{"zip": "12345"}

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",  // still the new email you set
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "12345"                      // and this change as well
}

Since this PATCH from the post office doesn't concern itself with email, only zip code, if it is repeatedly applied, it will also get the same result: the zip code is set to the new value. A goes in, A comes out, therefore this is also idempotent.

The next day, you decide to send your PATCH again.

PATCH /users/1
{"email": "[email protected]"}

{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "address": "123 Mockingbird Lane",
  "city": "New York",
  "state": "NY",
  "zip": "12345"
}

Your patch has the same effect it had yesterday: it set the email address. A went in, A came out, therefore this is idempotent as well.

What I got wrong in my original answer

I want to draw an important distinction (something I got wrong in my original answer). Many servers will respond to your REST requests by sending back the new entity state, with your modifications (if any). So, when you get this response back, it is different from the one you got back yesterday, because the zip code is not the one you received last time. However, your request was not concerned with the zip code, only with the email. So your PATCH document is still idempotent - the email you sent in PATCH is now the email address on the entity.

So when is PATCH not idempotent, then?

For a full treatment of this question, I again refer you to Jason Hoetger's answer. I'm just going to leave it at that, because I honestly don't think I can answer this part better than he already has.

What does request.getParameter return?

String onevalue;   
if(request.getParameterMap().containsKey("one")!=false) 
{
onevalue=request.getParameter("one").toString();
}

SQL Query - how do filter by null or not null

I think this could work:

select * from tbl where statusid = isnull(@statusid,statusid)

Is there a way to split a widescreen monitor in to two or more virtual monitors?

What about just using virtual desktops? You can spread your windows around among multiple workspaces. Something like Virtual Dimension should give you most of that functionality. I use virtual desktops all the time on Linux, and it's the next best thing to multiple monitors.

Show values from a MySQL database table inside a HTML table on a webpage

Try this: (Completely Dynamic...)

<?php
$host    = "localhost";
$user    = "username_here";
$pass    = "password_here";
$db_name = "database_name_here";

//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}

//get results from database
$result = mysqli_query($connection,"SELECT * FROM products");
$all_property = array();  //declare an array for saving property

//showing property
echo '<table class="data-table">
        <tr class="data-heading">';  //initialize table tag
while ($property = mysqli_fetch_field($result)) {
    echo '<td>' . $property->name . '</td>';  //get field name for header
    array_push($all_property, $property->name);  //save those to array
}
echo '</tr>'; //end tr tag

//showing all data
while ($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    foreach ($all_property as $item) {
        echo '<td>' . $row[$item] . '</td>'; //get items using property value
    }
    echo '</tr>';
}
echo "</table>";
?>

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

First, open a terminal session and run:

cd /usr/local/
git status

to see if Homebrew is clean.

If it's dirty, run:

git reset --hard && git clean -df

then

brew doctor
brew update

If it's still broken, try this in your session:

sudo rm /System/Library/Frameworks/Ruby.framework/Versions/Current
sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/Current

This will force Homebrew to use Ruby 1.8 from the system's installation.

How to use XPath contains() here?

I already gave my +1 to Jeff Yates' solution.

Here is a quick explanation why your approach does not work. This:

//ul[@class='featureList' and contains(li, 'Model')]

encounters a limitation of the contains() function (or any other string function in XPath, for that matter).

The first argument is supposed to be a string. If you feed it a node list (giving it "li" does that), a conversion to string must take place. But this conversion is done for the first node in the list only.

In your case the first node in the list is <li><b>Type:</b> Clip Fan</li> (converted to a string: "Type: Clip Fan") which means that this:

//ul[@class='featureList' and contains(li, 'Type')]

would actually select a node!

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

Can multiple different HTML elements have the same ID if they're different elements?

SLaks answer is correct, but as an addendum note that the x/html specs specify that all ids must be unique within a (single) html document. Although it's not exactly what the op asked, there could be valid instances where the same id is attached to different entities across multiple pages.

Example:

(served to modern browsers) article#main-content {styled one way}
(served to legacy) div#main-content {styled another way}

Probably an antipattern though. Just leaving here as a devil's advocate point.

Signed to unsigned conversion in C - is it always safe?

Horrible Answers Galore

Ozgur Ozcitak

When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.

This is completely wrong.

Mats Fredriksson

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.

smh

Your addition operation causes the int to be converted to an unsigned int.

Wrong. Maybe it does and maybe it doesn't.

Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)

Wrong. It is either undefined behavior if it causes overflow or the value is preserved.

Anonymous

The value of i is converted to unsigned int ...

Wrong. Depends on the precision of an int relative to an unsigned int.

Taylor Price

As was previously answered, you can cast back and forth between signed and unsigned without a problem.

Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.

Now I can finally answer the question.

Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.

Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.

What is precision?

Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.

[Gotchas]

The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.

[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

How to create friendly URL in php?

According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:

RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1

And this maps requests from

/news.php?news_id=63

to

/news/63.html

Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:

<Files news>
    ForceType application/x-httpd-php
</Files>

And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:

<?php
    echo $_SERVER['PATH_INFO'];
    // outputs '/63.html'
?>

MySQL Data Source not appearing in Visual Studio

I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Why does Java's hashCode() in String use 31 as a multiplier?

According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.

(from Chapter 3, Item 9: Always override hashcode when you override equals, page 48)

Updating a date in Oracle SQL table

This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.

Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.

When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.

Whether that is the problem or not, you should always specify the date model:

UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');

Since you aren't specifying a time component - all Oracle DATE columns include a time, even if it's midnight - you could also use a date literal:

UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';

You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.

How to change Navigation Bar color in iOS 7?

To make Rajneesh071's code complete, you may also want to set the navigation bar's title color (and font, if you want) since the default behavior changed from iOS 6 to 7:

NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[ver objectAtIndex:0] intValue] >= 7)
{
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.translucent = NO;
    NSMutableDictionary *textAttributes = [[NSMutableDictionary alloc] initWithDictionary:mainNavController.navigationBar.titleTextAttributes];
    [textAttributes setValue:[UIColor whiteColor] forKey:UITextAttributeTextColor];
    self.navigationController.navigationBar.titleTextAttributes = textAttributes;
}
else
{
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}

How to add local jar files to a Maven project?

I'd like such solution - use maven-install-plugin in pom file:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>install-file</goal>
            </goals>
            <configuration>
                <file>lib/yourJar.jar</file>
                <groupId>com.somegroup.id</groupId>
                <artifactId>artefact-id</artifactId>
                <version>x.y.z</version>
                <packaging>jar</packaging>
            </configuration>
        </execution>
    </executions>
</plugin>

In this case you can perform mvn initialize and jar will be installed in local maven repo. Now this jar is available during any maven step on this machine (do not forget to include this dependency as any other maven dependency in pom with <dependency></dependency> tag). It is also possible to bind jar install not to initialize step, but any other step you like.

Python __call__ special method practical example

This is too late but I'm giving an example. Imagine you have a Vector class and a Point class. Both take x, y as positional args. Let's imagine you want to create a function that moves the point to be put on the vector.

4 Solutions

  • put_point_on_vec(point, vec)

  • Make it a method on the vector class. e.g my_vec.put_point(point)

  • Make it a method on the Point class. my_point.put_on_vec(vec)
  • Vector implements __call__, So you can use it like my_vec_instance(point)

This is actually part of some examples I'm working on for a guide for dunder methods explained with Maths that I'm gonna release sooner or later.

I left the logic of moving the point itself because this is not what this question is about

Why can't variables be declared in a switch statement?

I just wanted to emphasize slim's point. A switch construct creates a whole, first-class-citizen scope. So it is posible to declare (and initialize) a variable in a switch statement before the first case label, without an additional bracket pair:

switch (val) {  
  /* This *will* work, even in C89 */
  int newVal = 42;  
case VAL:
  newVal = 1984; 
  break;
case ANOTHER_VAL:  
  newVal = 2001;
  break;
}

CASCADE DELETE just once

No. To do it just once you would simply write the delete statement for the table you want to cascade.

DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);
DELETE FROM some_table;

How do I animate constraint changes?

Generally, you just need to update constraints and call layoutIfNeeded inside the animation block. This can be either changing the .constant property of an NSLayoutConstraint, adding remove constraints (iOS 7), or changing the .active property of constraints (iOS 8 & 9).

Sample Code:

[UIView animateWithDuration:0.3 animations:^{
    // Move to right
    self.leadingConstraint.active = false;
    self.trailingConstraint.active = true;

    // Move to bottom
    self.topConstraint.active = false;
    self.bottomConstraint.active = true;

    // Make the animation happen
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}];

Sample Setup:

Xcode Project so sample animation project.

Controversy

There are some questions about whether the constraint should be changed before the animation block, or inside it (see previous answers).

The following is a Twitter conversation between Martin Pilkington who teaches iOS, and Ken Ferry who wrote Auto Layout. Ken explains that though changing constants outside of the animation block may currently work, it's not safe and they should really be change inside the animation block. https://twitter.com/kongtomorrow/status/440627401018466305

Animation:

Sample Project

Here's a simple project showing how a view can be animated. It's using Objective C and animates the view by changing the .active property of several constraints. https://github.com/shepting/SampleAutoLayoutAnimation

How do you fade in/out a background color using jquery?

This exact functionality (3 second glow to highlight a message) is implemented in the jQuery UI as the highlight effect

https://api.jqueryui.com/highlight-effect/

Color and duration are variable

MySQL SELECT statement for the "length" of the field is greater than 1

select * from [tbl] where [link] is not null and len([link]) > 1

For MySQL user:

LENGTH([link]) > 1

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

Current time in microseconds in java

LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)

What is the Ruby <=> (spaceship) operator?

Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

For example, if I have an array of objects I can do things like this:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

How do I set the driver's python version in spark?

Run:

ls -l /usr/local/bin/python*

The first row in this example shows the python3 symlink. To set it as the default python symlink run the following:

ln -s -f /usr/local/bin/python3 /usr/local/bin/python

then reload your shell.

How to join entries in a set into one string?

Nor the set nor the list has such method join, string has it:

','.join(set(['a','b','c']))

By the way you should not use name list for your variables. Give it a list_, my_list or some other name because list is very often used python function.

JAX-WS and BASIC authentication, when user names and passwords are in a database

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are matching HTTP Basic Authentication mechanism that enable authentication process at the HTTP level and not at the application nor servlet level.

Basically, only the HTTP server will know the username and the password (and eventually application according to HTTP/application server specification, such with Apache/PHP). With Tomcat/Java, add a login config BASIC in your web.xml and appropriate security-constraint/security-roles (roles that will be later associated to users/groups of real users).

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>YourRealm</realm-name>
</login-config>

Then, connect the realm at the HTTP server (or application server) level with the appropriate user repository. For tomcat you may look at JAASRealm, JDBCRealm or DataSourceRealm that may suit your needs.

http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html

How to set zoom level in google map

Your code below is zooming the map to fit the specified bounds:

addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);

If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  bounds.extend(pt);
}

If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.

If you will only ever have one marker, don't use fitBounds. Call setCenter, setZoom with the marker position and your desired zoom level.

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  map.setCenter(pt);
  map.setZoom(your desired zoom);
}

_x000D_
_x000D_
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
_x000D_
<html>

<head>
  <script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
  <script type="text/javascript">
    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
    var center = null;
    var map = null;
    var currentPopup;
    var bounds = new google.maps.LatLngBounds();

    function addMarker(lat, lng, info) {
      var pt = new google.maps.LatLng(lat, lng);
      map.setCenter(pt);
      map.setZoom(5);
      var marker = new google.maps.Marker({
        position: pt,
        icon: icon,
        map: map
      });
      var popup = new google.maps.InfoWindow({
        content: info,
        maxWidth: 300
      });
      google.maps.event.addListener(marker, "click", function() {
        if (currentPopup != null) {
          currentPopup.close();
          currentPopup = null;
        }
        popup.open(map, marker);
        currentPopup = popup;
      });
      google.maps.event.addListener(popup, "closeclick", function() {
        map.panTo(center);
        currentPopup = null;
      });
    }

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
        },
        navigationControl: true,
        navigationControlOptions: {
          style: google.maps.NavigationControlStyle.SMALL
        }
      });
      addMarker(27.703402, 85.311668, 'New Road');
      // center = bounds.getCenter();
      // map.fitBounds(bounds);

    }
  </script>
</head>

<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
  <div id="map"></div>
</body>

</html>
_x000D_
_x000D_
_x000D_

Difference between <input type='button' /> and <input type='submit' />

W3C make it clear, on the specification about Button element

Button may be seen as a generic class for all kind of Buttons with no default behavior.

W3C

You need to use a Theme.AppCompat theme (or descendant) with this activity

In my case, i was inflating a view with ApplicationContext. When you use ApplicationContext, theme/style is not applied, so although there was Theme.Appcompat in my style, it was not applied and caused this exception. More details: Theme/Style is not applied when inflater used with ApplicationContext

Angularjs - simple form submit

WARNING This is for Angular 1.x

If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.


ORIGINAL ANSWER

I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" name="form.firstname">    
        <br/><br/>

        Email Address: <br/><input type="text" ng-model="form.emailaddress"> 
        <br/><br/>

        <textarea rows="3" cols="25">
          Describe your reason for submitting this form ... 
        </textarea> 
        <br/>

        <input type="radio" ng-model="form.gender" value="female" />Female
        <input type="radio" ng-model="form.gender" value="male" />Male 
        <br/><br/>

        <input type="checkbox" ng-model="form.member" value="true"/> Already a member
        <input type="checkbox" ng-model="form.member" value="false"/> Not a member
        <br/>

        <input type="file" ng-model="form.file_profile" id="file_profile">
        <br/>

        <input type="file" ng-model="form.file_avatar" id="file_avatar">
        <br/><br/>

        <input type="submit">
    </form>
</div>

Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission. Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission

BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.

For general advice on angular form submission see the cookbook examples

UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission

The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.

Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.

socket programming multiple client to one server

I guess the problem is that you need to start a separate thread for each connection and call serverSocket.accept() in a loop to accept more than one connection.

It is not a problem to have more than one connection on the same port.

Eclipse/Maven error: "No compiler is provided in this environment"

Installed JRE In my case I solved the problem by removing duplicates of names, I kept only one with the name: jdk.1.8.0_101

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

plt.box(False)
plt.xticks([])
plt.yticks([])
plt.savefig('fig.png')

should do the trick.

Reverse Singly Linked List Java

public class SinglyLinkedListImpl<T> {

    private Node<T> head;

    public void add(T element) {
        Node<T> item = new Node<T>(element);
        if (head == null) {
            head = item;
        } else {
            Node<T> temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = item;
        }
    }

    private void reverse() {

        Node<T> temp = null;
        Node<T> next = null;
        while (head != null) {
            next = head.next;
            head.next = temp;
            temp = head;
            head = next;
        }
        head = temp;
    }

    void printList(Node<T> node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String a[]) {
        SinglyLinkedListImpl<Integer> sl = new SinglyLinkedListImpl<Integer>();
        sl.add(1);
        sl.add(2);
        sl.add(3);
        sl.add(4);

        sl.printList(sl.head);
        sl.reverse();
        sl.printList(sl.head);

    }

    static class Node<T> {

        private T data;
        private Node<T> next;

        public Node(T data) {
            super();
            this.data = data;
        }

    }
}

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

[contains(text(),'')] only returns true or false. It won't return any element results.

Checking if a field contains a string

As Mongo shell support regex, that's completely possible.

db.users.findOne({"username" : /.*son.*/});

If we want the query to be case-insensitive, we can use "i" option, like shown below:

db.users.findOne({"username" : /.*son.*/i});

See: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

Invariant Violation: _registerComponent(...): Target container is not a DOM element

I ran into similar/same error message. In my case, I did not have the target DOM node which is to render the ReactJS component defined. Ensure the HTML target node is well defined with appropriate "id" or "name", along with other HTML attributes (suitable for your design need)

no such file to load -- rubygems (LoadError)

I have also met the same problem using rbenv + passenger + nginx. my solution is simply adding these 2 line of code to your nginx config:

passenger_default_user root;
passenger_default_group root;

the detailed answer is here: https://stackoverflow.com/a/15777738/445908

What is "String args[]"? parameter in main method Java

String [] args is also how you declare an array of Strings in Java.

In this method signature, the array args will be filled with values when the method is called (as the other examples here show). Since you're learning though, it's worth understanding that this args array is just like if you created one yourself in a method, as in this:

public void foo() {
    String [] args = new String[2];
    args[0] = "hello";
    args[1] = "every";

    System.out.println("Output: " + args[0] + args[1]);

    // etc... the usage of 'args' here and in the main method is identical
}

What does "implements" do on a class?

You should look into Java's interfaces. A quick Google search revealed this page, which looks pretty good.

I like to think of an interface as a "promise" of sorts: Any class that implements it has certain behavior that can be expected of it, and therefore you can put an instance of an implementing class into an interface-type reference.

A simple example is the java.lang.Comparable interface. By implementing all methods in this interface in your own class, you are claiming that your objects are "comparable" to one another, and can be partially ordered.

Implementing an interface requires two steps:

  1. Declaring that the interface is implemented in the class declaration
  2. Providing definitions for ALL methods that are part of the interface.

Interface java.lang.Comparable has just one method in it, public int compareTo(Object other). So you need to provide that method.

Here's an example. Given this class RationalNumber:

public class RationalNumber
{
    public int numerator;
    public int denominator;

    public RationalNumber(int num, int den)
    {
        this.numerator = num;
        this.denominator = den;
    }
}

(Note: It's generally bad practice in Java to have public fields, but I am intending this to be a very simple plain-old-data type so I don't care about public fields!)

If I want to be able to compare two RationalNumber instances (for sorting purposes, maybe?), I can do that by implementing the java.lang.Comparable interface. In order to do that, two things need to be done: provide a definition for compareTo and declare that the interface is implemented.

Here's how the fleshed-out class might look:

public class RationalNumber implements java.lang.Comparable
{
    public int numerator;
    public int denominator;

    public RationalNumber(int num, int den)
    {
        this.numerator = num;
        this.denominator = den;
    }

    public int compareTo(Object other)
    {
        if (other == null || !(other instanceof RationalNumber))
        {
            return -1; // Put this object before non-RationalNumber objects
        }

        RationalNumber r = (RationalNumber)other;

        // Do the calculations by cross-multiplying. This isn't really important to
        // the answer, but the point is we're comparing the two rational numbers.
        // And no, I don't care if it's mathematically inaccurate.

        int myTotal = this.numerator * other.denominator;
        int theirTotal = other.numerator * this.denominator;

        if (myTotal < theirTotal) return -1;
        if (myTotal > theirTotal) return 1;
        return 0;
    }
}

You're probably thinking, what was the point of all this? The answer is when you look at methods like this: sorting algorithms that just expect "some kind of comparable object". (Note the requirement that all objects must implement java.lang.Comparable!) That method can take lists of ANY kind of comparable objects, be they Strings or Integers or RationalNumbers.

NOTE: I'm using practices from Java 1.4 in this answer. java.lang.Comparable is now a generic interface, but I don't have time to explain generics.

Where can I download Eclipse Android bundle?

The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:

  1. Start Eclipse, then select Help > Install New Software.
  2. Click Add, in the top-right corner.
  3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/
  4. Click OK.
  5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  7. Read and accept the license agreements, then click Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click OK
  8. When the installation completes, restart Eclipse.

Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.


Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.

Remove Item from ArrayList

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects.

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

WPF - add static items to a combo box

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

Key Value Pair Combobox in WPF

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

Best way to determine user's locale within browser

There's a difference between the user's preferred languages and the system/browser locale.

A user can configure preferred languages in the browser, and these will be used for navigator.language(s), and used when requesting resources from a server, to request content according to a list of language priorities.

However, the browser locale will decide how to render number, date, time and currency. This setting is likely the highest ranking language, but there is no guarantee. On Mac and Linux, the locale is decided by the system regardless of the user language preferences. On Windows is can be elected among the languages in the preferred list on Chrome.

By using Intl (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), developers can override/set the locale to use to render these things, but there are elements that cannot be overridden, such as the <input type="date"> format.

To properly extract this language, the only way I've found is:

(new Intl.NumberFormat()).resolvedOptions().locale

(Intl.NumberFormat().resolvedOptions().locale also seems to work)

This will create a new NumberFormat instance for the default locale and then reading back the locale of those resolved options.

What is Scala's yield?

It is used in sequence comprehensions (like Python's list-comprehensions and generators, where you may use yield too).

It is applied in combination with for and writes a new element into the resulting sequence.

Simple example (from scala-lang)

/** Turn command line arguments to uppercase */
object Main {
  def main(args: Array[String]) {
    val res = for (a <- args) yield a.toUpperCase
    println("Arguments: " + res.toString)
  }
}

The corresponding expression in F# would be

[ for a in args -> a.toUpperCase ]

or

from a in args select a.toUpperCase 

in Linq.

Ruby's yield has a different effect.

How to run an EXE file in PowerShell with parameters with spaces and quotes

You can run exe files in powershell different ways. For instance if you want to run unrar.exe and extract a .rar file you can simply write in powershell this:

$extract_path = "C:\Program Files\Containing folder";
$rar_to_extract = "C:\Path_to_arch\file.rar"; #(or.exe if its a big file)  
C:\Path_here\Unrar.exe x -o+ -c- $rar_to_extract $extract_path;

But sometimes, this doesn't work so you must use the & parameter as shown above: For instance, with vboxmanage.exe (a tool to manage virtualbox virtual machines) you must call the paramterers outside of the string like this, without quotes:

> $vmname = "misae_unrtes_1234123"; #(name too long, we want to change this)
> & 'C:\Program Files\Oracle\VirtualBox\VBoxManage.exe' modifyvm $vmname --name UBUNTU;

If you want to call simply a winrar archived file as .exe files, you can also unzip it with the invoke-command cmdlet and a Silent parameter /S (Its going to extract itself in the same folder than where it has been compressed).

> Invoke-Command -ScriptBlock { C:\Your-path\archivefile.exe /S };

So there are several ways to run .exe files with arguments in powershell.

Sometimes, one must find a workaround to make it work properly, which can require some further effort and pain :) depending on the way the .exe has been compiled or made bi its creators.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

How do you replace double quotes with a blank space in Java?

Strings are immutable, so you need to say

sInputString = sInputString("\"","");

not just the right side of the =

Calling a function of a module by using its name (a string)

none of what was suggested helped me. I did discover this though.

<object>.__getattribute__(<string name>)(<params>)

I am using python 2.66

Hope this helps

angularjs ng-style: background-image isn't working

This worked for me, curly braces are not required.

ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"

notification.icon here is scope variable.

Share variables between files in Node.js?

With a different opinion, I think the global variables might be the best choice if you are going to publish your code to npm, cuz you cannot be sure that all packages are using the same release of your code. So if you use a file for exporting a singleton object, it will cause issues here.

You can choose global, require.main or any other objects which are shared across files.

Otherwise, install your package as an optional dependency package can avoid this problem.

Please tell me if there are some better solutions.

How to acces external json file objects in vue.js app

Typescript projects (I have typescript in SFC vue components), need to set resolveJsonModule compiler option to true.

In tsconfig.json:

{
  "compilerOptions": {
    ...
    "resolveJsonModule": true,
    ...
  },
  ...
}

Happy coding :)

(Source https://www.typescriptlang.org/docs/handbook/compiler-options.html)

Explain why constructor inject is better than other options

Constructor injection is used when the class cannot function without the dependent class.

Property injection is used when the class can function without the dependent class.

As a concrete example, consider a ServiceRepository which depends on IService to do its work. Since ServiceRepository cannot function usefully without IService, it makes sense to have it injected via the constructor.

The same ServiceRepository class may use a Logger to do tracing. The ILogger can be injected via Property injection.

Other common examples of Property injection are ICache (another aspect in AOP terminology) or IBaseProperty (a property in the base class).

Django: Redirect to previous page after login

You do not need to make an extra view for this, the functionality is already built in.

First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request:

settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
)

Then add in the template you want the Login link:

base.html:

<a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a>

This will add a GET argument to the login page that points back to the current page.

The login template can then be as simple as this:

registration/login.html:

{% block content %}
<form method="post" action="">
  {{form.as_p}}
<input type="submit" value="Login">
</form>
{% endblock %}

Print series of prime numbers in python

A simpler and more efficient way of solving this is storing all prime numbers found previously and checking if the next number is a multiple of any of the smaller primes.

n = 1000
primes = [2]

for i in range(3, n, 2):
    if not any(i % prime == 0 for prime in primes):
        primes.append(i)

print(primes)

Note that any is a short circuit function, in other words, it will break the loop as soon as a truthy value is found.

How do you loop in a Windows batch file?

Try this code:

@echo off
color 02
set num1=0
set num2=1 
set terminator=5
:loop
set /a num1= %num1% + %num2%
if %num1%==%terminator% goto close
goto open
:close
echo %num1%
pause 
exit
:open
echo %num1%
goto loop

num1 is the number to be incremented and num2 is the value added to num1 and terminator is the value where the num1 will end. You can indicate different value for terminator in this statement (if %num1%==%terminator% goto close). This is the boolean expression goto close is the process if the boolean is true and goto open is the process if the boolean is false.

How to add a button dynamically in Android?

Try this code. It will work fine..

public class DynamicViewsActivity extends Activity {

Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_dynamic_views);
    ScrollView scrl=new ScrollView(this);
    final LinearLayout ll=new LinearLayout(this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(100, 500, 100, 200);
    scrl.addView(ll);
    Button add_btn=new Button(this);
    add_btn.setText("Click Here");

    ll.addView(add_btn, layoutParams);


    final Context context = this;

    add_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(context, App2Activity.class);
            startActivity(intent);
        }
    });
    this.setContentView(scrl);
}
}

How to index into a dictionary?

If you need an ordered dictionary, you can use odict.

Return index of highest value in an array

Function taken from http://www.php.net/manual/en/function.max.php

function max_key($array) {
    foreach ($array as $key => $val) {
        if ($val == max($array)) return $key; 
    }
}

$arr = array (
    '11' => 14,
    '10' => 9,
    '12' => 7,
    '13' => 7,
    '14' => 4,
    '15' => 6
);

die(var_dump(max_key($arr)));

Works like a charm

C++ printing spaces or tabs given a user input integer

cout << "Enter amount of spaces you would like (integer)" << endl; 
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
   cout << " " ;
}
cout <<endl;

mongod command not recognized when trying to connect to a mongodb server

Are you sure that you have specified the correct paths?

You need to be in the right directory, i.e.

C:\Program Files\MongoDB\bin

and the path you are installing into needs to be the correct one

i.e.

mongod --dbpath 
C:\Users\Name\Documents\myWebsites\nodetest1

A folder named "data" must also exist in your project folder.

I got the same error and this worked for me.

Circle line-segment collision detection algorithm?

This Java Function returns a DVec2 Object. It takes a DVec2 for the center of the circle, the radius of the circle, and a Line.

public static DVec2 CircLine(DVec2 C, double r, Line line)
{
    DVec2 A = line.p1;
    DVec2 B = line.p2;
    DVec2 P;
    DVec2 AC = new DVec2( C );
    AC.sub(A);
    DVec2 AB = new DVec2( B );
    AB.sub(A);
    double ab2 = AB.dot(AB);
    double acab = AC.dot(AB);
    double t = acab / ab2;

    if (t < 0.0) 
        t = 0.0;
    else if (t > 1.0) 
        t = 1.0;

    //P = A + t * AB;
    P = new DVec2( AB );
    P.mul( t );
    P.add( A );

    DVec2 H = new DVec2( P );
    H.sub( C );
    double h2 = H.dot(H);
    double r2 = r * r;

    if(h2 > r2) 
        return null;
    else
        return P;
}

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge.

I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved.

Hopefully this answer will help someone in the future.

Getting key with maximum value in dictionary?

A heap queue is a generalised solution which allows you to extract the top n keys ordered by value:

from heapq import nlargest

stats = {'a':1000, 'b':3000, 'c': 100}

res1 = nlargest(1, stats, key=stats.__getitem__)  # ['b']
res2 = nlargest(2, stats, key=stats.__getitem__)  # ['b', 'a']

res1_val = next(iter(res1))                       # 'b'

Note dict.__getitem__ is the method called by the syntactic sugar dict[]. As opposed to dict.get, it will return KeyError if a key is not found, which here cannot occur.

Perform commands over ssh with Python

Below example, incase if you want user inputs for hostname,username,password and port no.

  import paramiko

  ssh = paramiko.SSHClient()

  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())



  def details():

  Host = input("Enter the Hostname: ")

  Port = input("Enter the Port: ")

  User = input("Enter the Username: ")

  Pass = input("Enter the Password: ")

  ssh.connect(Host, Port, User, Pass, timeout=2)

  print('connected')

  stdin, stdout, stderr = ssh.exec_command("")

  stdin.write('xcommand SystemUnit Boot Action: Restart\n')

  print('success')

  details()

How to use adb command to push a file on device without sd card

This might be the best answer you'll may read. Setup Android Studio Then just go to view & Open Device Explorer. Right-click on the folder & just upload a file.

How do I get this javascript to run every second?

You can use setInterval:

var timer = setInterval( myFunction, 1000);

Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How to allow users to check for the latest app version from inside the app?

If it is an application on the Market, then on app start-up, fire an Intent to open up the Market app hopefully which will cause it to check for updates.

Otherwise implementing and update checker is fairly easy. Here is my code (roughly) for it:

String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
                                                 // should send the current version
                                                 // to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));

Of course you should rewrite this to do the request on a background thread but you get the idea.

If you like something a little but more complex but allows your app to automatically apply the update see here.

How do I specify the exit code of a console application in .NET?

Use ExitCode if your main has a void return signature, otherwise you need to "set" it by the value you return.

Environment.ExitCode Property

If the Main method returns void, you can use this property to set the exit code that will be returned to the calling environment. If Main does not return void, this property is ignored. The initial value of this property is zero.

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Although I've tried all the previous answers, only the following one worked out:

1 - Open Powershell (as Admin)

2 - Run:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

How to delete from multiple tables in MySQL?

The syntax looks right to me ... try to change it to use INNER JOIN ...

Have a look at this.

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

How to open link in new tab on html?

target="_blank" attribute will do the job. Just don't forget to add rel="noopener noreferrer" to solve the potential vulnerability. More on that here: https://dev.to/ben/the-targetblank-vulnerability-by-example

<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">Searcher</a>

Difference between ProcessBuilder and Runtime.exec()

The various overloads of Runtime.getRuntime().exec(...) take either an array of strings or a single string. The single-string overloads of exec() will tokenise the string into an array of arguments, before passing the string array onto one of the exec() overloads that takes a string array. The ProcessBuilder constructors, on the other hand, only take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.

So, for example, on Windows,

Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");

will run a DoStuff.exe program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");

will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2 in C:\. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");

or alternatively

List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);

Updating to latest version of CocoaPods?

For those with a sudo-less CocoaPods installation (i.e., you do not want to grant RubyGems admin privileges), you don't need the sudo command to update your CocoaPods installation:

gem install cocoapods

You can find out where the CocoaPods gem is installed with:

gem which cocoapods

If this is within your home directory, you should definitely run gem install cocoapods without using sudo.

Finally, to check which CocoaPods you are currently running type:

pod --version

How do you close/hide the Android soft keyboard using Java?

You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

This will force the keyboard to be hidden in all situations. In some cases, you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down the menu).

Note: If you want to do this in Kotlin, use: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

Kotlin Syntax

// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.hideSoftInputFromWindow(view.windowToken, 0)
}

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

Compress images on client side before uploading

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

You can try the demo here : http://makeitsolutions.com/labs/jic and get the sources here : https://github.com/brunobar79/J-I-C

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

Permissions error when connecting to EC2 via SSH on Mac OSx

I had the same problem using the AWS Toolkit for Eclipse. I created the Getting Started instance OK and opened a shell. However, the user was set to ec2-user. I used the Open Shell As... command and set the user to root. Then it worked.

How do I concatenate const/literal strings in C?

Avoid using strcat in C code. The cleanest and, most importantly, the safest way is to use snprintf:

char buf[256];
snprintf(buf, sizeof buf, "%s%s%s%s", str1, str2, str3, str4);

Some commenters raised an issue that the number of arguments may not match the format string and the code will still compile, but most compilers already issue a warning if this is the case.

How to replace all occurrences of a string in Javascript?

In string first element search and replace

_x000D_
_x000D_
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'_x000D_
var i = str.replace('"[','[').replace(']"',']');_x000D_
console.log(i,'//first element search and replace')
_x000D_
_x000D_
_x000D_

In string global search and replace

_x000D_
_x000D_
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'_x000D_
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');_x000D_
console.log(j,'//global search and replace')
_x000D_
_x000D_
_x000D_

Pure CSS to make font-size responsive based on dynamic amount of characters

The only way would probably be to set different widths for different screen sizes, but this approach is pretty inacurate and you should use a js solution.

h1 {
    font-size: 20px;
}

@media all and (max-device-width: 720px){
    h1 {
        font-size: 18px;
    }
}

@media all and (max-device-width: 640px){
    h1 {
        font-size: 16px;
    }
}

@media all and (max-device-width: 320px){
    h1 {
        font-size: 12px;
    }
}

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

Based on the comments left above I ran this under sqlplus instead of SQL Developer and the UPDATE statement ran perfectly, leaving me to believe this is an issue in SQL Developer particularly as there was no ORA error number being returned. Thank you for leading me in the right direction.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

"/openStudentPage" is the page that i want to open first, i did :

 @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
     return "redirect:/openStudentPage";
    }

@RequestMapping(value = "/openStudentPage", method = RequestMethod.GET)
public String listStudents(Model model) {
    model.addAttribute("student", new Student());
    model.addAttribute("listStudents", this.StudentService.listStudents());
    return "index";
}

mysql is not recognised as an internal or external command,operable program or batch

enter image description hereHere what I DO on MY PC I install all software that i usually used in G: partian not C: if my operating system is fall (win 10) , Do not need to reinstall them again and lost time , Then How windows work it update PATH automatic if you install any new programe or pice of softwore ,

SO

I must update PATH like these HERE! all my software i usually used 1- I created folder called Programe Files 2- I install all my programe data in these folder 3-and then going to PATH and add it Dont forget ;

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\HashiCorp\Vagrant\bin;G:\xampp\php;G:\xampp\mysql\bin;G:\Program Files (x86)\heroku\bin;G:\Program Files (x86)\Git\bin;G:\Program Files (x86)\composer;G:\Program Files (x86)\nodejs;G:\Program Files (x86)\Sublime Text 3;G:\Program Files (x86)\Microsoft VS Code\bin;G:\Program Files (x86)\cygwin64\bin

enter image description here

PHPUnit assert that an exception was thrown?

PhpUnit is an amazing library, but this specific point is a bit frustrating. This is why we can use the turbotesting-php opensource library which has a very convenient assertion method to help us testing exceptions. It is found here:

https://github.com/edertone/TurboTesting/blob/master/TurboTesting-Php/src/main/php/utils/AssertUtils.php

And to use it, we would simply do the following:

AssertUtils::throwsException(function(){

    // Some code that must throw an exception here

}, '/expected error message/');

If the code we type inside the anonymous function does not throw an exception, an exception will be thrown.

If the code we type inside the anonymous function throws an exception, but its message does not match the expected regexp, an exception will also be thrown.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

CSS3 transition doesn't work with display property

max-height

.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}

.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}

https://www.codehive.io/boards/bUoLvRg

Selecting default item from Combobox C#

    ComboBox1.Text = ComboBox1.Items(0).ToString

This code is show you Combobox1 first item in Vb.net

Is it possible to animate scrollTop with jQuery?

Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).

$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            alert('this alert will popup twice');
        }
    }
);

Here's how you can avoid the double callback.

var completeCalled = false;
$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            if(!completeCalled){
                completeCalled = true;
                alert('this alert will popup once');
            }
        }
    }
);

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

In Git, how do I figure out what my current revision is?

This gives you just the revision.

git rev-parse HEAD

swift 3.0 Data to String?

for swift 5

let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String?
print("testString > \(testString)")
//testString > This is a test string
print("somedata > \(String(describing: somedata))")
//somedata > Optional(21 bytes)
print("backToString > \(String(describing: backToString))")
//backToString > Optional("This is a test string")

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

What is so bad about singletons?

Monopoly is the devil and singletons with non-readonly/mutable state are the 'real' problem...

After reading Singletons are Pathological Liars as suggested in jason's answer I came across this little tidbit that provides the best presented example of how singletons are often misused.

Global is bad because:

  • a. It causes namespace conflict
  • b. It exposes the state in a unwarranted fashion

When it comes to Singletons

  • a. The explicit OO way of calling them, prevents the conflicts, so point a. is not an issue
  • b. Singletons without state are (like factories) are not a problem. Singletons with state can again fall in two categories, those which are immutable or write once and read many (config/property files). These are not bad. Mutable Singletons, which are kind of reference holders are the ones which you are speaking of.

In the last statement he's referring to the blog's concept of 'singletons are liars'.

How does this apply to Monopoly?

To start a game of monopoly, first:

  • we establish the rules first so everybody is on the same page
  • everybody is given an equal start at the beginning of the game
  • only one set of rules is presented to avoid confusion
  • the rules aren't allowed to change throughout the game

Now, for anybody who hasn't really played monopoly, these standards are ideal at best. A defeat in monopoly is hard to swallow because, monopoly is about money, if you lose you have to painstakingly watch the rest of the players finish the game, and losses are usually swift and crushing. So, the rules usually get twisted at some point to serve the self-interest of some of the players at the expense of the others.

So you're playing monopoly with friends Bob, Joe, and Ed. You're swiftly building your empire and consuming market share at an exponential rate. Your opponents are weakening and you start to smell blood (figuratively). Your buddy Bob put all of his money into gridlocking as many low-value properties as possible but his isn't receiving a high return on investment the way he expected. Bob, as a stroke of bad luck, lands on your Boardwalk and is excised from the game.

Now the game goes from friendly dice-rolling to serious business. Bob has been made the example of failure and Joe and Ed don't want to end up like 'that guy'. So, being the leading player you, all of a sudden, become the enemy. Joe and Ed start practicing under-the-table trades, behind-the-back money injections, undervalued house-swapping and generally anything to weaken you as a player until one of them rises to the top.

Then, instead of one of them winning, the process starts all over. All of a sudden, a finite set of rules becomes a moving target and the game degenerates into the type of social interactions that would make up the foundation of every high-rated reality TV show since Survivor. Why, because the rules are changing and there's no consensus on how/why/what they're supposed to represent, and more importantly, there's no one person making the decisions. Every player in the game, at that point, is making his/her own rules and chaos ensues until two of the players are too tired to keep up the charade and slowly give up.

So, if a rulebook for a game accurately represented a singleton, the monopoly rulebook would be an example of abuse.

How does this apply to programming?

Aside from all of the obvious thread-safety and synchronization issues that mutable singletons present... If you have one set of data, that is capable of being read/manipulated by multiple different sources concurrently and exists during the lifetime of the application execution, it's probably a good time to step back and ask "am I using the right type of data structure here".

Personally, I have seen a programmer abuse a singleton by using it as some sort of twisted cross-thread database store within an application. Having worked on the code directly, I can attest that it was a slow (because of all the thread locks needed to make it thread-safe) and a nightmare to work on (because of the unpredictable/intermittent nature of synchronization bugs), and nearly impossible to test under 'production' conditions. Sure, a system could have been developed using polling/signaling to overcome some of the performance issues but that wouldn't solve the issues with testing and, why bother when a 'real' database can already accomplish the same functionality in a much more robust/scalable manner.

A Singleton is only an option if you need what a singleton provides. A write-one read-only instance of an object. That same rule should cascade to the object's properties/members as well.

How can I insert data into Database Laravel?

The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:

Route::post('test/register', array('uses'=>'TestController@create'));

Also, you need to hash your passwords:

public function create()
{
    $user = new User;

    $user->username = Input::get('username');
    $user->email = Input::get('email');
    $user->password = Hash::make(Input::get('password'));
    $user->save();

    return Redirect::back();
}

And I removed the line:

$user= Input::all();

Because in the next command you replace its contents with

$user = new User;

To debug your Input, you can, in the first line of your controller:

dd( Input::all() );

It will display all fields in the input.

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

Assign an initial value to radio button as checked

If you are using react-redux for your application and if you want to show data which is in the redux store, you can set "checked" option as below.

<label>Male</label>

 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "0"}
 />



 <label>Female</label>
 <input
   type="radio"
   name="gender"
   defaultChecked={this.props.gender == "1"}
 />

presenting ViewController with NavigationViewController swift

My navigation bar was not showing, so I have used the following method in Swift 2 iOS 9

let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as! Dashboard

// Creating a navigation controller with viewController at the root of the navigation stack.
let navController = UINavigationController(rootViewController: viewController)
self.presentViewController(navController, animated:true, completion: nil)

openpyxl - adjust column width size

With openpyxl 3.0.3 the best way to modify the columns is with the DimensionHolder object, which is a dictionary that maps each column to a ColumnDimension object. ColumnDimension can get parameters as bestFit, auto_size (which is an alias of bestFit) and width. Personally, auto_size doesn't work as expected and I had to use width and fogured out that the best width for the column is len(cell_value) * 1.23.

To get the value of each cell it's necessary to iterate over each one, but I personally didn't use it because in my project I just had to write worksheets, so I got the longest string in each column directly on my data.

The example below just shows how to modify the column dimensions:

import openpyxl
from openpyxl.worksheet.dimensions import ColumnDimension, DimensionHolder
from openpyxl.utils import get_column_letter

wb = openpyxl.load_workbook("Example.xslx")
ws = wb["Sheet1"]

dim_holder = DimensionHolder(worksheet=ws)

for col in range(ws.min_column, ws.max_column + 1):
    dim_holder[get_column_letter(col)] = ColumnDimension(ws, min=col, max=col, width=20)

ws.column_dimensions = dim_holder

Callback to a Fragment from a DialogFragment

I was facing a similar problem. The solution that I found out was :

  1. Declare an interface in your DialogFragment just like James McCracken has explained above.

  2. Implement the interface in your activity (not fragment! That is not a good practice).

  3. From the callback method in your activity, call a required public function in your fragment which does the job that you want to do.

Thus, it becomes a two-step process : DialogFragment -> Activity and then Activity -> Fragment

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
  public:
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();
    }

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
    }

  private:
    std::chrono::high_resolution_clock::time_point from;
};

int main (int argc, char* argv[])
{
  double total;
  Timer timer;



  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";


  return 0;
}

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

What is Java String interning?

Since strings are objects and since all objects in Java are always stored only in the heap space, all strings are stored in the heap space. However, Java keeps strings created without using the new keyword in a special area of the heap space, which is called "string pool". Java keeps the strings created using the new keyword in the regular heap space.

The purpose of the string pool is to maintain a set of unique strings. Any time you create a new string without using the new keyword, Java checks whether the same string already exists in the string pool. If it does, Java returns a reference to the same String object and if it does not, Java creates a new String object in the string pool and returns its reference. So, for example, if you use the string "hello" twice in your code as shown below, you will get a reference to the same string. We can actually test this theory out by comparing two different reference variables using the == operator as shown in the following code:

String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); //prints true

String str3 = new String("hello");
String str4 = new String("hello");

System.out.println(str1 == str3); //prints false
System.out.println(str3 == str4); //prints false 

== operator is simply checks whether two references point to the same object or not and returns true if they do. In the above code, str2 gets the reference to the same String object which was created earlier. However, str3 and str4 get references to two entirely different String objects. That is why str1 == str2 returns true but str1 == str3 and str3 == str4 return false . In fact, when you do new String("hello"); two String objects are created instead of just one if this is the first time the string "hello" is used in the anywhere in program - one in the string pool because of the use of a quoted string, and one in the regular heap space because of the use of new keyword.

String pooling is Java's way of saving program memory by avoiding the creation of multiple String objects containing the same value. It is possible to get a string from the string pool for a string created using the new keyword by using String's intern method. It is called "interning" of string objects. For example,

String str1 = "hello";
String str2 = new String("hello");
String str3 = str2.intern(); //get an interned string obj

System.out.println(str1 == str2); //prints false
System.out.println(str1 == str3); //prints true

OCP Java SE 11 Programmer, Deshmukh

How do I measure the execution time of JavaScript code with callbacks?

Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime) internally.

var perfy = require('perfy');

function end(label) {
    return function (err, saved) {
        console.log(err ? 'Error' : 'Saved'); 
        console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
    };
}

for (var i = 1; i < LIMIT; i++) {
    var label = 'db-save-' + i;
    perfy.start(label); // <——— start and mark time
    db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}

Note that each time perfy.end(label) is called, that instance is auto-destroyed.

Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How do relative file paths work in Eclipse?

This is really similar to another question. How should I load files into my Java application?

How should I load my files into my Java Application?

You do not want to load your files in by:

C:\your\project\file.txt

this is bad!

You should use getResourceAsStream.

InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);

And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

jQuery OR Selector?

Daniel A. White Solution works great for classes.

I've got a situation where I had to find input fields like donee_1_card where 1 is an index.

My solution has been

$("input[name^='donee']" && "input[name*='card']")

Though I am not sure how optimal it is.

Wait until flag=true

Try avoid while loop as it could be blocking your code, use async and promises.

Just wrote this library:

https://www.npmjs.com/package/utilzed

There is a function waitForTrue

import utilzed from 'utilzed'

const checkCondition = async () => {
  // anything that you are polling for to be expecting to be true
  const response = await callSomeExternalApi();
  return response.success;
}

// this will waitForTrue checkCondition to be true
// checkCondition will be called every 100ms
const success = await utilzed.waitForTrue(100, checkCondition, 1000);

if (success) {
  // Meaning checkCondition function returns true before 1000 ms
  return;
}

// meaning after 1000ms the checkCondition returns false still
// handle unsuccessful "poll for true" 

Is it possible to insert multiple rows at a time in an SQLite database?

I'm surprised that no one has mentioned prepared statements. Unless you are using SQL on its own and not within any other language, then I would think that prepared statements wrapped in a transaction would be the most efficient way of inserting multiple rows.

Grant Select on all Tables Owned By Specific User

yes, its possible, run this command:

lets say you have user called thoko

grant select any table, insert any table, delete any table, update any table to thoko;

note: worked on oracle database

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

Calling method using JavaScript prototype

I did not understand what exactly you're trying to do, but normally implementing object-specific behaviour is done along these lines:

function MyClass(name) {
    this.name = name;
}

MyClass.prototype.doStuff = function() {
    // generic behaviour
}

var myObj = new MyClass('foo');

var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
    // do specialised stuff
    // how to call the generic implementation:
    MyClass.prototype.doStuff.call(this /*, args...*/);
}

jQuery append text inside of an existing paragraph tag

If you want to append text or html to span then you can do it as below.

$('p span#add_here').append('text goes here');

append will add text to span tag at the end.

to replace entire text or html inside of span you can use .text() or .html()

Which browsers support <script async="async" />?

From your referenced page:

http://googlecode.blogspot.com/2009/12/google-analytics-launches-asynchronous.html

Firefox 3.6 is the first browser to officially offer support for this new feature. If you're curious, here are more details on the official HTML5 async specification.

Swing vs JavaFx for desktop applications

What will be cleaner and easier to maintain?

All things being equal, probably JavaFX - the API is much more consistent across components. However, this depends much more on how the code is written rather than what library is used to write it.

And what will be faster to build from scratch?

Highly dependent on what you're building. Swing has more components around for it (3rd party as well as built in) and not all of them have made their way to the newer JavaFX platform yet, so there may be a certain amount of re-inventing the wheel if you need something a bit custom. On the other hand, if you want to do transitions / animations / video stuff then this is orders of magnitude easier in FX.

One other thing to bear in mind is (perhaps) look and feel. If you absolutely must have the default system look and feel, then JavaFX (at present) can't provide this. Not a big must have for me (I prefer the default FX look anyway) but I'm aware some policies mandate a restriction to system styles.

Personally, I see JavaFX as the "up and coming" UI library that's not quite there yet (but more than usable), and Swing as the borderline-legacy UI library that's fully featured and supported for the moment, but probably won't be so much in the years to come (and therefore chances are FX will overtake it at some point.)

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Is there a way to do repetitive tasks at intervals?

If you want to stop it in any moment ticker

ticker := time.NewTicker(500 * time.Millisecond)
go func() {
    for range ticker.C {
        fmt.Println("Tick")
    }
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()

If you do not want to stop it tick:

tick := time.Tick(500 * time.Millisecond)
for range tick {
    fmt.Println("Tick")
}

jquery how to use multiple ajax calls one after the end of the other

Place them inside of the success: of the one it relies on.

$.ajax({
    url: 'http://www.xxxxxxxxxxxxx',
    data: {name: 'xxxxxx'},
    dataType: 'jsonp',
    success: function(data){

        // do stuff

        // call next ajax function
        $.ajax({ xxx });
    }
});

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

How to get screen width and height

WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);

Log.d("WIDTH: ", String.valueOf(d.getWidth()));
Log.d("HEIGHT: ", String.valueOf(d.getHeight()));

How to call Oracle MD5 hash function?

I would do:

select DBMS_CRYPTO.HASH(rawtohex('foo') ,2) from dual;

output:

DBMS_CRYPTO.HASH(RAWTOHEX('FOO'),2)
--------------------------------------------------------------------------------
ACBD18DB4CC2F85CEDEF654FCCC4A4D8

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.

ie.

composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

How do you debug React Native?

adb logcat *:S ReactNative:V ReactNativeJS:V

run this in terminal for android log.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Probably the jstl libraries are missing from your classpath/not accessible by tomcat.

You need to add at least the following jar files in your WEB-INF/lib directory:

  • jsf-impl.jar
  • jsf-api.jar
  • jstl.jar

How to remove first and last character of a string?

SOLUTION 1

def spaceMeOut(str1):

   print(str1[1:len(str1)-1])

str1='Hello'

print(spaceMeOut(str1))

SOLUTION 2

def spaceMeOut(str1):

  res=str1[1:len(str1)-1]

  print('{}'.format(res))

str1='Hello'

print(spaceMeOut(str1))

How do I convert a number to a letter in Java?

Another variant:

private String getCharForNumber(int i) {
    if (i > 25 || i < 0) {
        return null;
    }
    return new Character((char) (i + 65)).toString();
}

How to Delete Session Cookie?

This needs to be done on the server-side, where the cookie was issued.

FAIL - Application at context path /Hello could not be started

I've had the same problem, was missing a slash in servlet url in web.xml

replace

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>jsonservice</url-pattern>
</servlet-mapping>

with

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>/jsonservice</url-pattern>
</servlet-mapping>

HTML5 Canvas and Anti-aliasing

It's now 2018, and we finally have cheap ways to do something around it...

Indeed, since the 2d context API now has a filter property, and that this filter property can accept SVGFilters, we can build an SVGFilter that will keep only fully opaque pixels from our drawings, and thus eliminate the default anti-aliasing.

So it won't deactivate antialiasing per se, but provides a cheap way both in term of implementation and of performances to remove all semi-transparent pixels while drawing.

I am not really a specialist of SVGFilters, so there might be a better way of doing it, but for the example, I'll use a <feComponentTransfer> node to grab only fully opaque pixels.

_x000D_
_x000D_
var ctx = canvas.getContext('2d');_x000D_
ctx.fillStyle = '#ABEDBE';_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.font = '14px sans-serif';_x000D_
ctx.textAlign = 'center';_x000D_
_x000D_
// first without filter_x000D_
ctx.fillText('no filter', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
// then with filter_x000D_
ctx.setTransform(1, 0, 0, 1, 120, 0);_x000D_
ctx.filter = 'url(#remove-alpha)';_x000D_
// and do the same ops_x000D_
ctx.fillText('no alpha', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
_x000D_
// to remove the filter_x000D_
ctx.filter = 'none';_x000D_
_x000D_
_x000D_
function drawArc() {_x000D_
  ctx.beginPath();_x000D_
  ctx.arc(60, 80, 50, 0, Math.PI * 2);_x000D_
  ctx.stroke();_x000D_
}_x000D_
_x000D_
function drawTriangle() {_x000D_
  ctx.beginPath();_x000D_
  ctx.moveTo(60, 150);_x000D_
  ctx.lineTo(110, 230);_x000D_
  ctx.lineTo(10, 230);_x000D_
  ctx.closePath();_x000D_
  ctx.stroke();_x000D_
}_x000D_
// unrelated_x000D_
// simply to show a zoomed-in version_x000D_
var zCtx = zoomed.getContext('2d');_x000D_
zCtx.imageSmoothingEnabled = false;_x000D_
canvas.onmousemove = function drawToZoommed(e) {_x000D_
  var x = e.pageX - this.offsetLeft,_x000D_
    y = e.pageY - this.offsetTop,_x000D_
    w = this.width,_x000D_
    h = this.height;_x000D_
    _x000D_
  zCtx.clearRect(0,0,w,h);_x000D_
  zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);_x000D_
}
_x000D_
<svg width="0" height="0" style="position:absolute;z-index:-1;">_x000D_
  <defs>_x000D_
    <filter id="remove-alpha" x="0" y="0" width="100%" height="100%">_x000D_
      <feComponentTransfer>_x000D_
        <feFuncA type="discrete" tableValues="0 1"></feFuncA>_x000D_
      </feComponentTransfer>_x000D_
      </filter>_x000D_
  </defs>_x000D_
</svg>_x000D_
_x000D_
<canvas id="canvas" width="250" height="250" ></canvas>_x000D_
<canvas id="zoomed" width="250" height="250" ></canvas>
_x000D_
_x000D_
_x000D_

And for the ones that don't like to append an <svg> element in their DOM, you can also save it as an external svg file and set the filter property to path/to/svg_file.svg#remove-alpha.

PowerShell: how to grep command output?

Try this:

PS C:\> ipconfig /displaydns | Select-String -Pattern 'www.yahoo.com' -Context 0,7

>     www.yahoo.com
      ----------------------------------------
>     Record Name . . . . . : www.yahoo.com
      Record Type . . . . . : 5
      Time To Live  . . . . : 27
      Data Length . . . . . : 8
      Section . . . . . . . : Answer
      CNAME Record  . . . . : new-fp-shed.wg1.b.yahoo.com

How to deal with "data of class uneval" error from ggplot2?

Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

qplot(data=..., x=...,y=..., ...)

ggplot(data=..., aes(x=...,y=...,...))

It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

How can I properly handle 404 in ASP.NET MVC?

Adding my solution, which is almost identical to Herman Kan's, with a small wrinkle to allow it to work for my project.

Create a custom error controller:

public class Error404Controller : BaseController
{
    [HttpGet]
    public ActionResult PageNotFound()
    {
        Response.StatusCode = 404;
        return View("404");
    }
}

Then create a custom controller factory:

public class CustomControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return controllerType == null ? new Error404Controller() : base.GetControllerInstance(requestContext, controllerType);
    }
}

Finally, add an override to the custom error controller:

protected override void HandleUnknownAction(string actionName)
{
    var errorRoute = new RouteData();
    errorRoute.Values.Add("controller", "Error404");
    errorRoute.Values.Add("action", "PageNotFound");
    new Error404Controller().Execute(new RequestContext(HttpContext, errorRoute));
}

And that's it. No need for Web.config changes.

Importing a GitHub project into Eclipse

As mentioned in Alain Beauvois's answer, and now (Q4 2013) better explained in

Copy the URL from GitHub and select in Eclipse from the menu the

File ? Import ? Git ? Projects from Git

http://wiki.eclipse.org/images/5/5a/Egit-0.9-import-projects-select-repository.png


If the Git repo isn't cloned yet:

In> order to checkout a remote project, you will have to clone its repository first.
Open the Eclipse Import wizard (e.g. File => Import), select Git => Projects from Git and click Next.
Select “URI” and click Next.
Now you will have to enter the repository’s location and connection data. Entering the URI will automatically fill some fields. Complete any other required fields and hit Next. If you use GitHub, you can copy the URI from the web page.

Select all branches you wish to clone and hit Next again.

Hit the Clone… button to open another wizard for cloning Git repositories.

http://eclipsesource.com/blogs/wp-content/uploads/2012/12/14-282x300.png


Original answer (July 2011)

First, if your "Working Directory" is C:\Users, that is odd, since it would mean you have cloned the GitHub repo directly within C:\Users (i.e. you have a .git directory in C:\Users)

Usually, you would clone a GitHub repo in "any directory of your choice\theGitHubRepoName".

As described in the EGit user Manual page:

In any case (unless you create a "bare" Repository, but that's not discussed here), the new Repository is essentially a folder on the local hard disk which contains the "working directory" and the metadata folder.
The metadata folder is a dedicated child folder named ".git" and often referred to as ".git-folder". It contains the actual repository (i.e. the Commits, the References, the logs and such).

The metadata folder is totally transparent to the Git client, while the working directory is used to expose the currently checked out Repository content as files for tools and editors.

Typically, if these files are to be used in Eclipse, they must be imported into the Eclipse workspace in one way or another. In order to do so, the easiest way would be to check in .project files from which the "Import Existing Projects" wizard can create the projects easily. Thus in most cases, the structure of a Repository containing Eclipse projects would look similar to something like this:

See also the Using EGit with Github section.


My working directory is now c:\users\projectname\.git

You should have the content of that repo checked out in c:\users\projectname (in other words, you should have more than just the .git).

So then I try to import the project using the eclipse "import" option.
When I try to import selecting the option "Use the new projects wizard", the source code is not imported.

That is normal.

If I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project.

Again normal.

When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?

No, that would only create an empty project.
If that project is created in c:\users\projectname, you can then declare the eisting source directory in that project.
Since it is defined in the same working directory than the Git repo, that project should then appear as "versioned".

You could also use the "Import existing project" option, if your GitHub repo had versioned the .project and .classpath file, but that may not be the case here.

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

If you are sitting at the merge commit then this shows the diffs:

git diff HEAD~1..HEAD

If you're not at the merge commit then just replace HEAD with the merge commit. This method seems like the simplest and most intuitive.

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

where is create-react-app webpack config and files?

I know it's pretty late, but for future people stumbling upon this issue, if you want to have access to the webpack config of CRA, there's no other way except you have to run:

$ npm run eject

However, with ejection, you'll strip away yourself from CRA pipeline of updates, therefore from the point of ejection, you have to maintain it yourself.

I have come across this issue many times, and therefore I've created a template for react apps which have most of the same config as CRA, but also additional perks (like styled-components, jest unit test, Travis ci for deployments, prettier, ESLint, etc...) to make the maintenance easier. Check out the repo.

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

How about this :

public ActionResult GetGrid()
{
   string url = "login.html";
   return new HttpStatusCodeResult(System.Net.HttpStatusCode.Redirect,url)
}

And then

$(document).ajaxError(function (event, jqxhr, settings, thrownError) { 
   if (jqxhr.status == 302) {
      location.href = jqxhr.statusText;
   }           
});

Or

error: function (a, b, c) {
       if (a.status == 302) {
         location.href = a.statusText;
       }  
}

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

Updates were rejected because the tip of your current branch is behind its remote counterpart

This is how I solved my problem

Let's assume the upstream branch is the one that you forked from and origin is your repo and you want to send an MR/PR to the upstream branch.

You already have let's say about 4 commits and you are getting Updates were rejected because the tip of your current branch is behind.

Here is what I did

First, squash all your 4 commits

git rebase -i HEAD~4

You'll get a list of commits with pick written on them. (opened in an editor)

example

pick fda59df commit 1
pick x536897 commit 2
pick c01a668 commit 3
pick c011a77 commit 4

to

pick fda59df commit 1
squash x536897 commit 2
squash c01a668 commit 3
squash c011a77 commit 4

After that, you can save your combined commit

Next

You'll need to stash your commit

Here's how

git reset --soft HEAD~1
git stash

now rebase with your upstream branch

git fetch upstream beta && git rebase upstream/beta

Now pop your stashed commit

git stash pop

commit these changes and push them

git add -A
git commit -m "[foo] - foobar commit"
git push origin fix/#123 -f

Function to close the window in Tkinter

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
        button.pack()
        self.root.mainloop()

    def quit(self):
        self.root.destroy()

app = App()

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

Now, with EF Core you can convert data type transparently in your AppDbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
      // i.e. Store TimeSpan as string (custom)
      modelBuilder
        .Entity<YourClass>()
        .Property(x => x.YourTimeSpan)
        .HasConversion(
            timeSpan => timeSpan.ToString(), // To DB
            timeSpanString => TimeSpan.Parse(timeSpanString) // From DB
        );

    // i.e. Store TimeSpan as string (using TimeSpanToStringConverter)
    modelBuilder
        .Entity<YourClass>()
        .Property(x => x.YourTimeSpan)
        .HasConversion(new TimeSpanToStringConverter());

      // i.e. Store TimeSpan as number of ticks (custom)
      modelBuilder
        .Entity<YourClass>()
        .Property(x => x.YourTimeSpan)
        .HasConversion(
            timeSpan => timeSpan.Ticks, // To DB
            timeSpanString => TimeSpan.FromTicks(timeSpanString) // From DB
        );

    // i.e. Store TimeSpan as number of ticks (using TimeSpanToTicksConverter)
    modelBuilder
        .Entity<YourClass>()
        .Property(x => x.YourTimeSpan)
        .HasConversion(new TimeSpanToTicksConverter());
}

Two submit buttons in one form

You formaction for multiple submit button in one form example

 <input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress"> 
 <input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress"> 

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty as the key. Otherwise it is assumed it is a property error. The custom error you're adding has the key 'error' so it will not display in when you call ValidationSummary(true). You need to add your custom error message with an empty key like this:

ModelState.AddModelError(string.Empty, ex.Message);

Javascript - Append HTML to container element without innerHTML

<div id="Result">
</div>

<script>
for(var i=0; i<=10; i++){
var data = "<b>vijay</b>";
 document.getElementById('Result').innerHTML += data;
}
</script>

assign the data for div with "+=" symbol you can append data including previous html data

Float sum with javascript

Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed() function:

var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?

inherit from two classes in C#

Do you mean you want Class C to be the base class for A & B in that case.

public abstract class C
{
    public abstract void Method1();

    public abstract void Method2();
}

public class A : C
{
    public override void Method1()
    {
        throw new NotImplementedException();
    }

    public override void Method2()
    {
        throw new NotImplementedException();
    }
}


public class B : C
{
    public override void Method1()
    {
        throw new NotImplementedException();
    }

    public override void Method2()
    {
        throw new NotImplementedException();
    }
}

Select distinct values from a list using LINQ in C#

Try,

var newList = 
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();

Inline functions in C#?

Do you mean inline functions in the C++ sense? In which the contents of a normal function are automatically copied inline into the callsite? The end effect being that no function call actually happens when calling a function.

Example:

inline int Add(int left, int right) { return left + right; }

If so then no, there is no C# equivalent to this.

Or Do you mean functions that are declared within another function? If so then yes, C# supports this via anonymous methods or lambda expressions.

Example:

static void Example() {
  Func<int,int,int> add = (x,y) => x + y;
  var result = add(4,6);  // 10
}

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

connect to host localhost port 22: Connection refused

Check file /etc/ssh/sshd_config for Port number. Make sure it is 22.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How to convert nanoseconds to seconds using the TimeUnit enum?

TimeUnit Enum

The following expression uses the TimeUnit enum (Java 5 and later) to convert from nanoseconds to seconds:

TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS)

How to check if element in groovy array/hash/collection/list?

.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()

[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')

R define dimensions of empty data frame

Here a solution if you want an empty data frame with a defined number of rows and NO columns:

df = data.frame(matrix(NA, ncol=1, nrow=10)[-1]

Javascript ES6/ES5 find in array and change

My best approach is:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

items[items.findIndex(el => el.id === item.id)] = item;

Reference for findIndex

And in case you don't want to replace with new object, but instead to copy the fields of item, you can use Object.assign:

Object.assign(items[items.findIndex(el => el.id === item.id)], item)

as an alternative with .map():

Object.assign(items, items.map(el => el.id === item.id? item : el))

Functional approach:

Don't modify the array, use a new one, so you don't generate side effects

const updatedItems = items.map(el => el.id === item.id ? item : el)

Dump all documents of Elasticsearch

You can also dump elasticsearch data in JSON format by http request: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
CURL -XPOST 'https://ES/INDEX/_search?scroll=10m'
CURL -XPOST 'https://ES/_search/scroll' -d '{"scroll": "10m", "scroll_id": "ID"}'

Inserting a PDF file in LaTeX

\includegraphics{myfig.pdf}

Wait one second in running program

Wait function using timers, no UI locks.

public void wait(int milliseconds)
{
    var timer1 = new System.Windows.Forms.Timer();
    if (milliseconds == 0 || milliseconds < 0) return;

    // Console.WriteLine("start wait timer");
    timer1.Interval = milliseconds;
    timer1.Enabled  = true;
    timer1.Start();

    timer1.Tick += (s, e) =>
    {
        timer1.Enabled = false;
        timer1.Stop();
        // Console.WriteLine("stop wait timer");
    };

    while (timer1.Enabled)
    {
        Application.DoEvents();
    }
}

Usage: just placing this inside your code that needs to wait:

wait(1000); //wait one second

c++ integer->std::string conversion. Simple function?

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

Calling a method every x minutes

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);

How do I put a border around an Android textview?

Here is my 'simple' helper class which returns an ImageView with the border. Just drop this in your utils folder, and call it like this:

ImageView selectionBorder = BorderDrawer.generateBorderImageView(context, borderWidth, borderHeight, thickness, Color.Blue);

Here is the code.

/**
 * Because creating a border is Rocket Science in Android.
 */
public class BorderDrawer
{
    public static ImageView generateBorderImageView(Context context, int borderWidth, int borderHeight, int borderThickness, int color)
    {
        ImageView mask = new ImageView(context);

        // Create the square to serve as the mask
        Bitmap squareMask = Bitmap.createBitmap(borderWidth - (borderThickness*2), borderHeight - (borderThickness*2), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(squareMask);

        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(color);
        canvas.drawRect(0.0f, 0.0f, (float)borderWidth, (float)borderHeight, paint);

        // Create the darkness bitmap
        Bitmap solidColor = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(solidColor);

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(color);
        canvas.drawRect(0.0f, 0.0f, borderWidth, borderHeight, paint);

        // Create the masked version of the darknessView
        Bitmap borderBitmap = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(borderBitmap);

        Paint clearPaint = new Paint();
        clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

        canvas.drawBitmap(solidColor, 0, 0, null);
        canvas.drawBitmap(squareMask, borderThickness, borderThickness, clearPaint);

        clearPaint.setXfermode(null);

        ImageView borderView = new ImageView(context);
        borderView.setImageBitmap(borderBitmap);

        return borderView;
    }
}

Infinite Recursion with Jackson JSON and Hibernate JPA issue

You may use @JsonIgnore to break the cycle (reference).

You need to import org.codehaus.jackson.annotate.JsonIgnore (legacy versions) or com.fasterxml.jackson.annotation.JsonIgnore (current versions).

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How can I force component to re-render with hooks in React?

You should preferably only have your component depend on state and props and it will work as expected, but if you really need a function to force the component to re-render, you could use the useState hook and call the function when needed.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
function Foo() {_x000D_
  const [, forceUpdate] = useState();_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(forceUpdate, 2000);_x000D_
  }, []);_x000D_
_x000D_
  return <div>{Date.now()}</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Foo />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

Resize image in PHP

I would suggest an easy way:

function resize($file, $width, $height) {
    switch(pathinfo($file)['extension']) {
        case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
        case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
        default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
    }
}

Deserializing JSON data to C# using JSON.NET

Building off of bbant's answer, this is my complete solution for deserializing JSON from a remote URL.

using Newtonsoft.Json;
using System.Net.Http;

namespace Base
{
    public class ApiConsumer<T>
    {
        public T data;
        private string url;

        public CalendarApiConsumer(string url)
        {
            this.url = url;
            this.data = getItems();
        }

        private T getItems()
        {
            T result = default(T);
            HttpClient client = new HttpClient();

            // This allows for debugging possible JSON issues
            var settings = new JsonSerializerSettings
            {
                Error = (sender, args) =>
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }
                }
            };

            using (HttpResponseMessage response = client.GetAsync(this.url).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result, settings);
                }
            }
            return result;
        }
    }
}

Usage would be like:

ApiConsumer<FeedResult> feed = new ApiConsumer<FeedResult>("http://example.info/feeds/feeds.aspx?alt=json-in-script");

Where FeedResult is the class generated using the Xamasoft JSON Class Generator

Here is a screenshot of the settings I used, allowing for weird property names which the web version could not account for.

Xamasoft JSON Class Generator

Is it possible to make abstract classes in Python?

Most of the answers inherit the base class to define the abstract methods. But this is not always useful. What if you want to define an abstract method at runtime?

For example in java we can do this

class UserClass { ...

BaseClass f = new BaseClass() {
    public void method() {
        system.out.println( "this is a test" )
    }
};

}

So what to do if we need to implement that, so in that case

class BaseClass:

    def __init__(self, func ):
        self.function = func

    def abstract_function(self ):
        if not self.function:
            raise NotImplementedError("function not implemented") 
        else:
            return self.function()

    def run(self ):
        self.abstract_function()

def func():
    print('this is a test')

bc = BaseClass( func )
bc.run()

should work