Programs & Examples On #Symbol table

A `symbol table` is a data structure that maps each identifier in a program's source code to information relating to its declaration or appearance in the source.

Calling Member Functions within Main C++

declare it "static" like this:

static void MyClass::printInformation() { return; }

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

Connect to SQL Server Database from PowerShell

The answer are as below for Window authentication

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

What is Java Servlet?

If you are beginner, I think this tutorial may give basic idea about What Servlet is ...

Some valuable points are below from the given link.

Servlet technology is used to create web application which resides at server side and generates dynamic web page.

Servlet can be described in many ways, depending on the context.

  • Servlet is a technology i.e. used to create web application.
  • Servlet is an API that provides many interfaces and classes including documentations.
  • Servlet is an interface that must be implemented for creating any servlet.
  • Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.
  • Servlet is a web component that is deployed on the server to create dynamic web page. Reference:Here.

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

Get top 1 row of each group

Try this:

SELECT [DocumentID]
    ,[tmpRez].value('/x[2]', 'varchar(20)') AS [Status]
    ,[tmpRez].value('/x[3]', 'datetime') AS [DateCreated]
FROM (
    SELECT [DocumentID]
        ,cast('<x>' + max(cast([ID] AS VARCHAR(10)) + '</x><x>' + [Status] + '</x><x>' + cast([DateCreated] AS VARCHAR(20))) + '</x>' AS XML) AS [tmpRez]
    FROM DocumentStatusLogs
    GROUP BY DocumentID
    ) AS [tmpQry]

How do I declare an array with a custom class?

In order to create an array of objects, the objects need a constructor that doesn't take any paramters (that creates a default form of the object, eg. with both strings empty). This is what the error message means. The compiler automatically generates a constructor which creates an empty object unless there are any other constructors.

If it makes sense for the array elements to be created empty (in which case the members acquire their default values, in this case, empty strings), you should:

-Write an empty constructor:

class name {
  public:
    string first;
    string last;

  name() { }
  name(string a, string b){
    first = a;
    last = b;
  }
};

-Or, if you don't need it, remove the existing constructor.

If an "empty" version of your class makes no sense, there is no good solution to provide initialisation paramters to all the elements of the array at compile time. You can:

  • Have a constructor create an empty version of the class anyway, and an init() function which does the real initialisation
  • Use a vector, and on initialisation create the objects and insert them into the vector, either using vector::insert or a loop, and trust that not doing it at compile time doesn't matter.
  • If the object can't be copied either, you can use an array/vector of smart pointers to the object and allocate them on initialisation.
  • If you can use C++11 I think (?) you can use initialiser lists to initialise a vector and intialise it (I'm not sure if that works with any contructor or only if the object is created from a single value of another type). Eg: .
 std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };

`

Convert sqlalchemy row object to python dict

Here is a super simple way of doing it

row2dict = lambda r: dict(r.items())

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"

Remove all the elements that occur in one list from another

Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in l3:

l3 = [x for x in l1 if x not in l2]

l3 will contain [1, 6].

How can I disable selected attribute from select2() dropdown Jquery?

The below code also works fine for Select2 3.x

For Enable Select Box:

$('#foo').select2('enable');

For Disable Select Box:

$('#foo').select2('disable');

jsfiddle: http://jsfiddle.net/DcunN/

Tar archiving that takes input from a list of files

On Solaris, you can use the option -I to read the filenames that you would normally state on the command line from a file. In contrast to the command line, this can create tar archives with hundreds of thousands of files (just did that).

So the example would read

tar -cvf allfiles.tar -I mylist.txt

Get the (last part of) current directory name in C#

rather then using the '/' for the call to split, better to use the Path.DirectorySeparatorChar :

like so:

path.split(Path.DirectorySeparatorChar).Last() 

Bash foreach loop

xargs --arg-file inputfile cat

This will output the filename followed by the file's contents:

xargs --arg-file inputfile -I % sh -c "echo %; cat %"

JavaScript - Hide a Div at startup (load)

Using CSS you can just set display:none for the element in a CSS file or in a style attribute

#div { display:none; }
<div id="div"></div>



<div style="display:none"></div>

or having the js just after the div might be fast enough too, but not as clean

What is a difference between unsigned int and signed int in C?

Because it's all just about memory, in the end all the numerical values are stored in binary.

A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.

When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Selecting element by data attribute with jQuery

I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.

_x000D_
_x000D_
var elements = document.querySelectorAll('[data-customerID="22"]');_x000D_
_x000D_
elements[0].innerHTML = 'it worked!';
_x000D_
<a data-customerID='22'>test</a>
_x000D_
_x000D_
_x000D_

Info:

Warning: Permanently added the RSA host key for IP address

The IP addresses have changed again.

github publishes the list of used IP addresses here so you can check the IP address in your message against github's list:

https://help.github.com/articles/about-github-s-ip-addresses/

Or more precisely:

https://api.github.com/meta

It looks like this (as I write this answer!):

verifiable_password_authentication  true
github_services_sha "4159703d573ee6f602e304ed25b5862463a2c73d"
hooks   
0   "192.30.252.0/22"
1   "185.199.108.0/22"
git 
0   "192.30.252.0/22"
1   "185.199.108.0/22"
2   "18.195.85.27/32"
3   "18.194.104.89/32"
4   "35.159.8.160/32"
pages   
0   "192.30.252.153/32"
1   "192.30.252.154/32"
importer    
0   "54.87.5.173"
1   "54.166.52.62"
2   "23.20.92.3"

If you are unsure whether your IP address is contained in the above list use an CIDR calculator like http://www.subnet-calculator.com/cidr.php to show the valid IP range.

E. g. for 140.82.112.0/20 the IP range is 140.82.112.0 - 140.82.127.255

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];
}

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];
}

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc
    ];
}

and then output them in a template:

<ul>
<?php foreach($data as $row): ?>
    <li><?=$row['name']?></li>
<?php endforeach ?>
</ul>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Alternatively, you can use Inner Queries to do so.

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!

VBA test if cell is in a range

If the two ranges to be tested (your given cell and your given range) are not in the same Worksheet, then Application.Intersect throws an error. Thus, a way to avoid it is with something like

Sub test_inters(rng1 As Range, rng2 As Range)
    If (rng1.Parent.Name = rng2.Parent.Name) Then
        Dim ints As Range
        Set ints = Application.Intersect(rng1, rng2)
        If (Not (ints Is Nothing)) Then
            ' Do your job
        End If
    End If
End Sub

CSS: Background image and padding

You can just add the padding to tour block element and add background-origin style like so:

.block {
  position: relative;
  display: inline-block;
  padding: 10px 12px;
  border:1px solid #e5e5e5;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-origin: content-box;
  background-image: url(_your_image_);
  height: 14rem;
  width: 10rem;
}

You can check several https://www.w3schools.com/cssref/css3_pr_background-origin.asp

Set HTML element's style property in javascript

You can try grabbing the cssText and className.

var css1 = table.rows[1].style.cssText;
var css2 = table.rows[2].style.cssText;
var class1 = table.rows[1].className;
var class2 = table.rows[2].className;

// sort

// loop
    if (i%2==0) {
        table.rows[i].style.cssText = css1;
        table.rows[i].className = class1;
    } else {
        table.rows[i].style.cssText = css2;
        table.rows[i].className = class2;
    }

Not entirely sure about browser compatibility with cssText, though.

jQuery click event not working in mobile browsers

I had the same problem and fixed it by adding "mousedown touchstart"

$(document).on("mousedown touchstart", ".className", function() { // your code here });

inested of others

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I faced the same issue while trying to build a jar file of my project application using mvn clean install, though the application was working fine while running from Eclipse.

The issue was, indeed too naive, that I had not set the JAVA_HOME environment variable. All I had to do is set JAVA_HOME environment variable to JDK directory, make sure it is not till "\bin" and without semi-colon ";".

enter image description here

How I understood it is as:

The application worked fine in Eclipse as JRE System Library was referring to JRE inside the JDK folder instead of external JRE folder without JDK. [As explained very well in other answers]

This configuration does not apply to maven command that we run on command prompt. It will still look for JAVA_HOME variable to access the JRE System library and when it is not found it refers to external JRE folder without JDK.

JSONResult to String

You can also use Json.NET.

return JsonConvert.SerializeObject(jsonResult.Data);

jQuery .slideRight effect

Another solution is by using .animate() and appropriate CSS.

e.g.

   $('#mydiv').animate({ marginLeft: "100%"} , 4000);

JS Fiddle

How to zoom in/out an UIImage object when user pinches screen?

The simplest way to do this, if all you want is pinch zooming, is to place your image inside a UIWebView (write small amount of html wrapper code, reference your image, and you're basically done). The more complcated way to do this is to use touchesBegan, touchesMoved, and touchesEnded to keep track of the user's fingers, and adjust your view's transform property appropriately.

How to hide a column (GridView) but still access its value?

You can do it programmatically:

grid0.Columns[0].Visible = true;
grid0.DataSource = dt;
grid0.DataBind();
grid0.Columns[0].Visible = false;

In this way you set the column to visible before databinding, so the column is generated. The you set the column to not visible, so it is not displayed.

What is the correct JSON content type?

In Spring you have a defined type: MediaType.APPLICATION_JSON_VALUE which is equivalent to application/json.

String.Format like functionality in T-SQL?

Not exactly, but I would check out some of the articles on string handling (amongst other things) by "Phil Factor" (geddit?) on Simple Talk.

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

How to solve "The specified service has been marked for deletion" error

Deleting registry keys as suggested above got my service stuck in the stopping state. The following procedure worked for me:

open task manager > select services tab > select the service > right click and select "go to process" > right click on the process and select End process

Service should be gone after that

Handle Guzzle exception and get HTTP body

Guzzle 6.x

Per the docs, the exception types you may need to catch are:

  • GuzzleHttp\Exception\ClientException for 400-level errors
  • GuzzleHttp\Exception\ServerException for 500-level errors
  • GuzzleHttp\Exception\BadResponseException for both (it's their superclass)

Code to handle such errors thus now looks something like this:

$client = new GuzzleHttp\Client;
try {
    $client->get('http://google.com/nosuchpage');    
}
catch (GuzzleHttp\Exception\ClientException $e) {
    $response = $e->getResponse();
    $responseBodyAsString = $response->getBody()->getContents();
}

How can I find the number of elements in an array?

int a[20];
int length;
length = sizeof(a) / sizeof(int);

and you can use another way to make your code not be hard-coded to int

Say if you have an array array

you just need to:

int len = sizeof(array) / sizeof(array[0]);

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

file_get_contents() how to fix error "Failed to open stream", "No such file"

The URL is missing the protocol information. PHP thinks it is a filesystem path and tries to access the file at the specified location. However, the location doesn't actually exist in your filesystem and an error is thrown.

You'll need to add http or https at the beginning of the URL you're trying to get the contents from:

$json = json_decode(file_get_contents('http://...'));

As for the following error:

Unable to find the wrapper - did you forget to enable it when you configured PHP?

Your Apache installation probably wasn't compiled with SSL support. You could manually try to install OpenSSL and use it, or use cURL. I personally prefer cURL over file_get_contents(). Here's a function you can use:

function curl_get_contents($url)
{
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

Usage:

$url = 'https://...';
$json = json_decode(curl_get_contents($url));

How to check Network port access and display useful message?

Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.

I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.

This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!

function Test-Port {

    [CmdletBinding()]
    Param (
        [string] $ComputerName,
        [int] $Port,
        [int] $Delay = 1,
        [int] $Count = 3
    )

    function Test-TcpClient ($IPAddress, $Port) {

        $TcpClient = New-Object Net.Sockets.TcpClient
        Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}

        If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
        Return $False

    }

    function Invoke-Test ($ComputerName, $Port) {

        Try   { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString } 
        Catch { Return $False }

        [array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
        If ($Results -contains $True) { Return $True } Else { Return $False }

    }

    for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
    {
        if ($i -ge $Count) {
            Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
            Return $false
        }

        Write-Warning "Port $Port not open, retrying..."
        Sleep $Delay
    }

    Return $true

}

How to use concerns in Rails 4

So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.

As an example, I'll put one well known pattern, the taggable pattern:

# app/models/product.rb
class Product
  include Taggable

  ...
end

# app/models/concerns/taggable.rb
# notice that the file name has to match the module name 
# (applying Rails conventions for autoloading)
module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, as: :taggable
    has_many :tags, through: :taggings

    class_attribute :tag_limit
  end

  def tags_string
    tags.map(&:name).join(', ')
  end

  def tags_string=(tag_string)
    tag_names = tag_string.to_s.split(', ')

    tag_names.each do |tag_name|
      tags.build(name: tag_name)
    end
  end

  # methods defined here are going to extend the class, not the instance of it
  module ClassMethods

    def tag_limit(value)
      self.tag_limit_value = value
    end

  end

end

So following the Product sample, you can add Taggable to any class you desire and share its functionality.

This is pretty well explained by DHH:

In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.

How can I add shadow to the widget in flutter?

Use BoxDecoration with BoxShadow.

Here is a visual demo manipulating the following options:

  • opacity
  • x offset
  • y offset
  • blur radius
  • spread radius

The animated gif doesn't do so well with colors. You can try it yourself on a device.

enter image description here

Here is the full code for that demo:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ShadowDemo(),
      ),
    );
  }
}

class ShadowDemo extends StatefulWidget {
  @override
  _ShadowDemoState createState() => _ShadowDemoState();
}

class _ShadowDemoState extends State<ShadowDemo> {
  var _image = NetworkImage('https://placebear.com/300/300');

  var _opacity = 1.0;
  var _xOffset = 0.0;
  var _yOffset = 0.0;
  var _blurRadius = 0.0;
  var _spreadRadius = 0.0;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Center(
          child:
          Container(
            decoration: BoxDecoration(
              color: Color(0xFF0099EE),
              boxShadow: [
                BoxShadow(
                  color: Color.fromRGBO(0, 0, 0, _opacity),
                  offset: Offset(_xOffset, _yOffset),
                  blurRadius: _blurRadius,
                  spreadRadius: _spreadRadius,
                )
              ],
            ),
            child: Image(image:_image, width: 100, height: 100,),
          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Padding(
            padding: const EdgeInsets.only(bottom: 80.0),
            child: Column(
              children: <Widget>[
                Spacer(),
                Slider(
                  value: _opacity,
                  min: 0.0,
                  max: 1.0,
                  onChanged: (newValue) =>
                  {
                    setState(() => _opacity = newValue)
                  },
                ),
                Slider(
                  value: _xOffset,
                  min: -100,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _xOffset = newValue)
                  },
                ),
                Slider(
                  value: _yOffset,
                  min: -100,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _yOffset = newValue)
                  },
                ),
                Slider(
                  value: _blurRadius,
                  min: 0,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _blurRadius = newValue)
                  },
                ),
                Slider(
                  value: _spreadRadius,
                  min: 0,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _spreadRadius = newValue)
                  },
                ),
              ],
            ),
          ),
        )
      ],
    );
  }
}

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


What method in the String class returns only the first N characters?

string.Substring(0,n); // 0 - start index and n - number of characters

Skipping Iterations in Python

Something like this?

for i in xrange( someBigNumber ):
    try:
        doSomethingThatMightFail()
    except SomeException, e:
        continue
    doSomethingWhenNothingFailed()

Adding a 'share by email' link to website

<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>

Instructions

First, insert these lines wherever you want within your newsletter code. Then:

  1. Change "INSERT URL" to whatever website holds the shared content.
  2. Change "INSERT TITLE" to the title of the article.
  3. Change "INSERT SUMMARY" to a short summary of the article.
  4. Change "INSERT IMAGE URL" to an image that will be shared with the rest of the content.
  5. Change "INSERT DOMAIN NAME" to your domain name.
  6. Change "INSERT PUBLISHERID" to your publisher ID (if you have an account, if not, remove "[INSERT PUBLISHERID]" or sign up!)

If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.

Load jQuery with Javascript and use jQuery

Using require.js you can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:

I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautions you may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repo and reflected by the following code sample:

<title>jQuery+RequireJS Sample Page</title>
   <script src="scripts/require.js"></script>
   <script>
   require({
       baseUrl: 'scripts',
       paths: {
           jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
       },
       priority: ['jquery']
    }, ['main']);
    </script>

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

If you want to update your project using SVN then first of all:

  1. Go to the path on which your project is stored through command prompt.

  2. Use the command SVN update

That's it.

How do you find the row count for all your tables in Postgres

There's three ways to get this sort of count, each with their own tradeoffs.

If you want a true count, you have to execute the SELECT statement like the one you used against each table. This is because PostgreSQL keeps row visibility information in the row itself, not anywhere else, so any accurate count can only be relative to some transaction. You're getting a count of what that transaction sees at the point in time when it executes. You could automate this to run against every table in the database, but you probably don't need that level of accuracy or want to wait that long.

The second approach notes that the statistics collector tracks roughly how many rows are "live" (not deleted or obsoleted by later updates) at any time. This value can be off by a bit under heavy activity, but is generally a good estimate:

SELECT schemaname,relname,n_live_tup 
  FROM pg_stat_user_tables 
  ORDER BY n_live_tup DESC;

That can also show you how many rows are dead, which is itself an interesting number to monitor.

The third way is to note that the system ANALYZE command, which is executed by the autovacuum process regularly as of PostgreSQL 8.3 to update table statistics, also computes a row estimate. You can grab that one like this:

SELECT 
  nspname AS schemaname,relname,reltuples
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE 
  nspname NOT IN ('pg_catalog', 'information_schema') AND
  relkind='r' 
ORDER BY reltuples DESC;

Which of these queries is better to use is hard to say. Normally I make that decision based on whether there's more useful information I also want to use inside of pg_class or inside of pg_stat_user_tables. For basic counting purposes just to see how big things are in general, either should be accurate enough.

What's the difference between next() and nextLine() methods from Scanner class?

I always prefer to read input using nextLine() and then parse the string.

Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.

A useful tool for parsing data from nextLine() would be str.split("\\s+").

String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces

For more information regarding the Scanner class or String class refer to the following links.

Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

is there a require for json in node.js

You even can use require of your JSON without specifying the extension .json. It will let you change the file extension to .js without any changes in your imports.

assuming we have ./myJsonFile.json in the same directory.

const data = require('./myJsonFile')

If in the future you'll change ./myJsonFile.json to ./myJsonFile.js nothing should be changed in the import.

What is the use of a cursor in SQL Server?

Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.

However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.

In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.

How to execute Python scripts in Windows?

Can you execute python.exe from any map? If you do not, chek if you have proper values for python.exe in PATH enviroment

Are you in same directory than blah.py. Check this by issuing command -> edit blah.py and check if you can open this file

EDIT:

In that case you can not. (python arg means that you call python.exe whit some parameters which python assume that is filename of script you want to run)

You can create bat file whit lines in your path map and run .bat file

Example:
In one of Path maps create blah.py.bat Edit file and put line

python C:\Somedir\blah.py

You can now run blah.py from anywere, becuase you do not need to put .bat extention when running bat files

Angular routerLink does not navigate to the corresponding component

Try changing the links as below:

  <ul class="nav navbar-nav item">
    <li>
        <a [routerLink]="['/home']" routerLinkActive="active">Home</a>
    </li>
    <li>
        <a [routerLink]="['/about']" routerLinkActive="active">About this</a>
    </li>
  </ul>

Also, add the following in the header of index.html:

<base href="/">

TypeLoadException says 'no implementation', but it is implemented

I faced almost same issue. I was scratching my head what is causing this error. I cross checked, all the methods were implemented.

On Googling I got this link among other. Based on @Paul McLink comment, This two steps resolved the issue.

  1. Restart Visual Studio
  2. Clean, Build (Rebuild)

and the error gone.

Restart VS Plugin

Thanks Paul :)

Hope this helps someone who come across this error :)

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

Identifier not found error on function call

At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:

void swapCase(char* name);

Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write

if ('A' <= name[i] && name[i] <= 'Z')
    name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
    name[i] += 'A' - 'a';

The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.

Good luck learning!

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

just enter the terminal

mysql -u root -p . than it will ask password to you

jQuery toggle CSS?

I would use the toggleClass function in jQuery and define the CSS to the class e.g.

/* start of css */
#user_button.active {
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    -webkit-border-bottom-right-radius: 5px; /* user-agent specific */
    -webkit-border-bottom-left-radius: 5px;
    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px; /* etc... */
}
/* start of js */
$('#user_button').click(function() {
    $('#user_options').toggle();
    $(this).toggleClass('active');
    return false;
})

How I can delete in VIM all text from current line to end of file?

:.,$d

This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.

How to convert a set to a list in python?

Simply type:

list(my_set)

This will turn a set in the form {'1','2'} into a list in the form ['1','2'].

How to get number of video views with YouTube API?

Here an example that I used in my TubeCount app.

I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.

var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[@yt:name='default'](@url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(@countHint)))";

var channel = "wiibart";

$.ajax({
    url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
    success: function(data){

        var len = data.feed.entry.length;

        for(var k =0; k<len; k++){
            var yt = data.feed.entry[k];
            v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
        }
    }
});

No provider for Http StaticInjectorError

In order to use Http in your app you will need to add the HttpModule to your app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ]

EDIT

As mentioned in the comment below, HttpModule is deprecated now, use import { HttpClientModule } from '@angular/common/http'; Make sure HttpClientModule in your imports:[] array

To find first N prime numbers in python

def isprime(n):
    if n <= 1:
        return False
    for x in range(2, n):
        if n % x == 0:
            return False
    else:
        return True

def list_prime(z):
    y = 0
    def to_infinity():
        index=0
        while 1:
            yield index
            index += 1
    for n in to_infinity():
        if y < z:
            if isprime(n):
                y = y + 1
                print(n, end='\n', flush=True)
        else:break
    print(f'\n {z} prime numbers are as above.')

# put your range below
list_prime(10)

Warning: A non-numeric value encountered

$sub_total_price = 0; 

foreach($booking_list as $key=>$value) {
        $sub_total_price += ($price * $quantity); 
}

echo $sub_total_price;

it's working 100% :)

How do I fix "The expression of type List needs unchecked conversion...'?

If you look at the javadoc for the class SyndFeed (I guess you are referring to the class com.sun.syndication.feed.synd.SyndFeed), the method getEntries() doesn't return java.util.List<SyndEntry>, but returns just java.util.List.

So you need an explicit cast for this.

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

How to convert String object to Boolean Object?

We created soyuz-to library to simplify this problem (convert X to Y). It's just a set of SO answers for similar questions. This might be strange to use the library for such a simple problem, but it really helps in a lot of similar cases.

import io.thedocs.soyuz.to;

Boolean aBoolean = to.Boolean("true");

Please check it - it's very simple and has a lot of other useful features

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

mkdir -p functionality in Python

mkdir -p gives you an error if the file already exists:

$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists

So a refinement to the previous suggestions would be to re-raise the exception if os.path.isdir returns False (when checking for errno.EEXIST).

(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend os.path.isdir instead of os.path.exists.

(Update) Per a suggestion in the comments, the full function would look like:

import os
def mkdirp(directory):
    if not os.path.isdir(directory):
        os.makedirs(directory) 

Error while installing json gem 'mkmf.rb can't find header files for ruby'

For those who are getting this on Mac OS X you may need to run the following command to install the XCode command-line tools, even if you already have XCode installed:

sudo xcode-select --install

Also you must agree the terms and conditions of XCode by running the following command:

sudo xcodebuild -license

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

How to download a branch with git?

Thanks to a related question, I found out that I need to "checkout" the remote branch as a new local branch, and specify a new local branch name.

git checkout -b newlocalbranchname origin/branch-name

Or you can do:

git checkout -t origin/branch-name

The latter will create a branch that is also set to track the remote branch.


Update: It's been 5 years since I originally posted this question. I've learned a lot and git has improved since then. My usual workflow is a little different now.

If I want to fetch the remote branches, I simply run:

git pull

This will fetch all of the remote branches and merge the current branch. It will display an output that looks something like this:

From github.com:andrewhavens/example-project
   dbd07ad..4316d29  master     -> origin/master
 * [new branch]      production -> origin/production
 * [new branch]      my-bugfix-branch -> origin/my-bugfix-branch
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 4316d296c55ac2e13992a22161fc327944bcf5b8.

Now git knows about my new my-bugfix-branch. To switch to this branch, I can simply run:

git checkout my-bugfix-branch

Normally, I would need to create the branch before I could check it out, but in newer versions of git, it's smart enough to know that you want to checkout a local copy of this remote branch.

Protecting cells in Excel but allow these to be modified by VBA script

I don't think you can set any part of the sheet to be editable only by VBA, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:

wksht.Unprotect()

and re-protect it after you're done:

wksht.Protect()

Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below. You can protect a sheet to be editable by VBA-only, but it appears the "UserInterfaceOnly" option can only be set when calling "Worksheet.Protect" in code.

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


Measure string size in Bytes in php

Do you mean byte size or string length?

Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.

Remove blank values from array using C#

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

Optimal number of threads per core

I agree with @Gonzalo's answer. I have a process that doesn't do I/O, and here is what I've found:

enter image description here

Note that all threads work on one array but different ranges (two threads do not access the same index), so the results may differ if they've worked on different arrays.

The 1.86 machine is a macbook air with an SSD. The other mac is an iMac with a normal HDD (I think it's 7200 rpm). The windows machine also has a 7200 rpm HDD.

In this test, the optimal number was equal to the number of cores in the machine.

Split string using a newline delimiter with Python

str.splitlines method should give you exactly that.

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

Find index of last occurrence of a sub-string using T-SQL

Hmm, I know this is an old thread, but a tally table could do this in SQL2000 (or any other database):

DECLARE @str CHAR(21),
        @delim CHAR(1)
 SELECT @str = 'Your-delimited-string',
        @delim = '-'

SELECT
    MAX(n) As 'position'
FROM
    dbo._Tally
WHERE
    substring(@str, _Tally.n, 1) = @delim

A tally table is just a table of incrementing numbers.

The substring(@str, _Tally.n, 1) = @delim gets the position of each delimiter, then you just get the maximum position in that set.

Tally tables are awesome. If you haven't used them before, there is a good article on SQL Server Central (Free reg, or just use Bug Me Not (http://www.bugmenot.com/view/sqlservercentral.com)).

*EDIT: Removed n <= LEN(TEXT_FIELD), as you can't use LEN() on the TEXT type. As long as the substring(...) = @delim remains though the result is still correct.

How to update one file in a zip archive

You can use: zip -u file.zip path/file_to_update

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

POST Multipart Form Data using Retrofit 2.0 including image

Don't use multiple parameters in the function name just go with simple few args convention that will increase the readability of codes, for this you can do like -

// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part); 
/* for single use or you can use by Part name with Request body */

// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts); 
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.

There can be multiple exceptions that you may encounter while using Retrofit, all of the exceptions documented as code, have a walkthrough to retrofit2/RequestFactory.java. you can able to two functions parseParameterAnnotation and parseMethodAnnotation where you can able to exception thrown, please go through this, it will save your much of time than googling/stackoverflow

Javascript change color of text and background to input value

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

First considerations are about mixing HTML, Javascript and CSS:

Why is using onClick() in HTML a bad practice?

Unobtrusive Javascript

Inline Styles vs Classes

I will be removing inline content and splitting these into their appropriate files.

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

Your function changeBackground sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.

CSS

#TheForm {
    margin-left: 396px;
}
#submitColor {
    margin-left: 48px;
    margin-top: 5px;
}

HTML

<form id="TheForm">
    <input id="color" type="text" />
    <br/>
    <input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>

Javascript

function changeBackground() {
    var color = document.getElementById("color").value; // cached

    // The working function for changing background color.
    document.bgColor = color;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = color;
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Source: w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values are written as 3 double digit numbers, starting with a # sign.

Update: as pointed out by @Ian

Hex can be either 3 or 6 characters long

Source: W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

For regex testing, I will use this pattern

/^#(?:[0-9a-f]{3}){1,2}$/i

but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern

function changeBackground() {
    var color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;

    if (rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Hex Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Here is a further modification that will allow colours by name along with by hex.

function changeBackground() {
    var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
        color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
        formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();

    if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

MySQL Update Column +1?

update post set count = count + 1 where id = 101

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

How to end C++ code

Either return a value from your main or use the exit function. Both take an int. It doesn't really matter what value you return unless you have an external process watching for the return value.

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

How should I declare default values for instance variables in Python?

Extending bp's answer, I wanted to show you what he meant by immutable types.

First, this is okay:

>>> class TestB():
...     def __init__(self, attr=1):
...         self.attr = attr
...     
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1

However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:

>>> class Test():
...     def __init__(self, attr=[]):
...         self.attr = attr
...     
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>> 

Note that both a and b have a shared attribute. This is often unwanted.

This is the Pythonic way of defining default values for instance variables, when the type is mutable:

>>> class TestC():
...     def __init__(self, attr=None):
...         if attr is None:
...             attr = []
...         self.attr = attr
...     
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]

The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.

jQuery changing css class to div

$(document).ready(function () {

            $("#divId").toggleClass('cssclassname'); // toggle class
});

**OR**

$(document).ready(function() {
        $("#objectId").click(function() {  // click or other event to change the div class
                $("#divId").toggleClass("cssclassname");     // toggle class
        )}; 
)};

HttpWebRequest using Basic authentication

The following construction was not working correctly for me:

request.Credentials = new NetworkCredential("user", "pass");

I have used CredentialCache instead:

CredentialCache credentialCache = new CredentialCache
{
    {
        new Uri($"http://{request.Host}/"), "Basic",
        new NetworkCredential("user", "pass")
    }
};
request.Credentials = credentialCache;

However, if you would like to add multiple basic auth credentials (for example if there is redirection that you are aware of) you can use following function that I have made:

private void SetNetworkCredential(Uri uriPrefix, string authType, NetworkCredential credential)
{
    if (request.Credentials == null)
    {
        request.Credentials = new CredentialCache();
    }

    if (request.Credentials.GetCredential(uriPrefix, authType) == null)
    {
        (request.Credentials as CredentialCache).Add(uriPrefix, authType, credential);
    }
}

I hope it will help somebody in the future.

Android: I lost my android key store, what should I do?

You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market

Do your absolute best to find that keystore!!

When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!

How do I compare two hashes?

If you want a nicely formatted diff, you can do this:

# Gemfile
gem 'awesome_print' # or gem install awesome_print

And in your code:

require 'ap'

def my_diff(a, b)
  as = a.ai(plain: true).split("\n").map(&:strip)
  bs = b.ai(plain: true).split("\n").map(&:strip)
  ((as - bs) + (bs - as)).join("\n")
end

puts my_diff({foo: :bar, nested: {val1: 1, val2: 2}, end: :v},
             {foo: :bar, n2: {nested: {val1: 1, val2: 3}}, end: :v})

The idea is to use awesome print to format, and diff the output. The diff won't be exact, but it is useful for debugging purposes.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Angular 2 - View not updating after model changes

Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.

Change your class to make an observable, that will emit results of new requests:

export class RecentDetectionComponent implements OnInit {

    recentDetections$: Observable<Array<RecentDetection>>;

    constructor(private recentDetectionService: RecentDetectionService) {
    }

    ngOnInit() {
        this.recentDetections$ = Observable.interval(5000)
            .exhaustMap(() => this.recentDetectionService.getJsonFromApi())
            .do(recent => console.log(recent[0].macAddress));
    }
}

And update your view to use AsyncPipe:

<tr *ngFor="let detected of recentDetections$ | async">
    ...
</tr>

Want to add, that it's better to make a service with a method that will take interval argument, and:

  • create new requests (by using exhaustMap like in code above);
  • handle requests errors;
  • stop browser from making new requests while offline.

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Get Folder Size from Windows Command Line

You can just add up sizes recursively (the following is a batch file):

@echo off
set size=0
for /r %%x in (folder\*) do set /a size+=%%~zx
echo %size% Bytes

However, this has several problems because cmd is limited to 32-bit signed integer arithmetic. So it will get sizes above 2 GiB wrong1. Furthermore it will likely count symlinks and junctions multiple times so it's at best an upper bound, not the true size (you'll have that problem with any tool, though).

An alternative is PowerShell:

Get-ChildItem -Recurse | Measure-Object -Sum Length

or shorter:

ls -r | measure -sum Length

If you want it prettier:

switch((ls -r|measure -sum Length).Sum) {
  {$_ -gt 1GB} {
    '{0:0.0} GiB' -f ($_/1GB)
    break
  }
  {$_ -gt 1MB} {
    '{0:0.0} MiB' -f ($_/1MB)
    break
  }
  {$_ -gt 1KB} {
    '{0:0.0} KiB' -f ($_/1KB)
    break
  }
  default { "$_ bytes" }
}

You can use this directly from cmd:

powershell -noprofile -command "ls -r|measure -sum Length"

1 I do have a partially-finished bignum library in batch files somewhere which at least gets arbitrary-precision integer addition right. I should really release it, I guess :-)

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

Setting JDK in Eclipse

Configuring JDKs

  1. Windows -> Preferences -> Installed JREs, to configured the installed JDKs
  2. Project Properties, Java Compiler, Enable project specific settings (or configure Workspace settings), JDK Compliance
  3. Project Properties, Java Build Path, Libraries, Add Library, JRE system library, Workspace default or Alternate JRE (one of the JREs configured in

Maven

BUT IF you are using maven, provided that you have your latest JRE (Windows/Preferences/Installed JREs) -for example JDK 1.8

You can select the level 1.6, 1.7, 1.8 by configuring the maven-compiler-plugin source and target attributes, like this

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

And ideally, if you have a parent pom, you can do it for all the modules (Eclipse projects) in the parent pom, in one single place.

Source and Target If we want to use the Java 8 language features the –source should be set to 1.8. Also, for the compiled classes to be compatible with JVM 1.8, the –target value should be 1.8.

Updating JRE library that is broken in many projects at once (with Maven)

Rather than updating one by one the JRE library, let Maven do it for you.

Selecting the projects and right-clicking for Maven -> Update Project, will set the system library to the path of the installed JDK, in case the paths are broken (because you installed a new JDK or imported from another computer, etc.) and set the JDK compliance according to the maven source and target setting in the pom.

Get elements by attribute when querySelectorAll is not available without using libraries?

A little modification on @kevinfahy 's answer, to allow getting the attribute by value if needed:

function getElementsByAttributeValue(attribute, value){
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++) {
    if (allElements[i].getAttribute(attribute) !== null) {
      if (!value || allElements[i].getAttribute(attribute) == value)
        matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

Extract images from PDF without resampling, in python?

PikePDF can do this with very little code:

from pikepdf import Pdf, PdfImage

filename = "sample-in.pdf"
example = Pdf.open(filename)

for i, page in enumerate(example.pages):
    for j, (name, raw_image) in enumerate(page.images.items()):
        image = PdfImage(raw_image)
        out = image.extract_to(fileprefix=f"{filename}-page{i:03}-img{j:03}")

extract_to will automatically pick the file extension based on how the image is encoded in the PDF.

If you want, you could also print some detail about the images as they get extracted:

        # Optional: print info about image
        w = raw_image.stream_dict.Width
        h = raw_image.stream_dict.Height
        f = raw_image.stream_dict.Filter
        size = raw_image.stream_dict.Length

        print(f"Wrote {name} {w}x{h} {f} {size:,}B {image.colorspace} to {out}")

which can print something like

Wrote /Im1 150x150 /DCTDecode 5,952B /ICCBased to sample2.pdf-page000-img000.jpg
Wrote /Im10 32x32 /FlateDecode 36B /ICCBased to sample2.pdf-page000-img001.png
...

See the docs for more that you can do with images, including replacing them in the PDF file.

`ui-router` $stateParams vs. $state.params

An interesting observation I made while passing previous state params from one route to another is that $stateParams gets hoisted and overwrites the previous route's state params that were passed with the current state params, but using $state.params doesn't.

When using $stateParams:

var stateParams        = {};
stateParams.nextParams = $stateParams; //{item_id:123}
stateParams.next       = $state.current.name;

$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{next:'app.details'}}

When using $state.params:

var stateParams        = {};
stateParams.nextParams = $state.params; //{item_id:123}
stateParams.next       = $state.current.name;

$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{item_id:123}}

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

Bloch doesn't quite go into this, but the rationale I've always heard/believed is that this is basic algebra. Hashes boil down to multiplication and modulus operations, which means that you never want to use numbers with common factors if you can help it. In other words, relatively prime numbers provide an even distribution of answers.

The numbers that make up using a hash are typically:

  • modulus of the data type you put it into (2^32 or 2^64)
  • modulus of the bucket count in your hashtable (varies. In java used to be prime, now 2^n)
  • multiply or shift by a magic number in your mixing function
  • The input value

You really only get to control a couple of these values, so a little extra care is due.

Compare two different files line by line in python

Try this:

from __future__ import with_statement

filename1 = "G:\\test1.TXT"
filename2 = "G:\\test2.TXT"


with open(filename1) as f1:
   with open(filename2) as f2:
      file1list = f1.read().splitlines()
      file2list = f2.read().splitlines()
      list1length = len(file1list)
      list2length = len(file2list)
      if list1length == list2length:
          for index in range(len(file1list)):
              if file1list[index] == file2list[index]:
                  print file1list[index] + "==" + file2list[index]
              else:                  
                  print file1list[index] + "!=" + file2list[index]+" Not-Equel"
      else:
          print "difference inthe size of the file and number of lines"

How to get the directory of the currently running file?

os.Executable: https://tip.golang.org/pkg/os/#Executable

filepath.EvalSymlinks: https://golang.org/pkg/path/filepath/#EvalSymlinks

Full Demo:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    var dirAbsPath string
    ex, err := os.Executable()
    if err == nil {
        dirAbsPath = filepath.Dir(ex)
        fmt.Println(dirAbsPath)
        return
    }

    exReal, err := filepath.EvalSymlinks(ex)
    if err != nil {
        panic(err)
    }
    dirAbsPath = filepath.Dir(exReal)
    fmt.Println(dirAbsPath)
}

How to disable textbox from editing?

As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.

enter image description here

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Creating folders inside a GitHub repository without using Git

Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

Saving an Object (Data persistence)

You can use anycache to do the job for you. It considers all the details:

  • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
  • It stores different objects to different files and reloads them properly.
  • Limits cache size
  • Allows cache clearing
  • Allows sharing of objects between multiple runs
  • Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')    
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

For any further details see the documentation

How to rotate x-axis tick labels in Pandas barplot

Pass param rot=0 to rotate the xticks:

import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()

yields plot:

enter image description here

What is the default Precision and Scale for a Number in Oracle?

I expand on spectra‘s answer so people don’t have to try it for themselves.

This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.

CREATE TABLE CUSTOMERS
(
  CUSTOMER_ID NUMBER NOT NULL,
  FOO FLOAT NOT NULL,
  JOIN_DATE DATE NOT NULL,
  CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
  CUSTOMER_NAME VARCHAR2(20) NOT NULL,
  CREDITRATING VARCHAR2(10)
);

select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS'; 

Which yields

COLUMN_NAME      DATA_TYPE  NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID      NUMBER     N        22        
FOO              FLOAT      N        22          126    
JOIN_DATE        DATE       N        7        
CUSTOMER_STATUS  VARCHAR2   N        8        
CUSTOMER_NAME    VARCHAR2   N        20        
CREDITRATING     VARCHAR2   Y        10    

How to add a linked source folder in Android Studio?

The right answer is:

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }
}

Furthermore, if your external source directory is not under src/main, you could use a relative path like this:

sourceSets {
    main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}

Difference between rake db:migrate db:reset and db:schema:load

As far as I understand, it is going to drop your database and re-create it based on your db/schema.rb file. That is why you need to make sure that your schema.rb file is always up to date and under version control.

How can I convert a stack trace to a string?

Old question, but I would just like to add the special case where you don't want to print all the stack, by removing some parts you are not actually interested in, excluding certain classes or packages.

Instead of a PrintWriter use a SelectivePrintWriter:

// This filters out this package and up.
String packageNameToFilter = "org.springframework";

StringWriter sw = new StringWriter();
PrintWriter pw = new SelectivePrintWriter(sw, packageNameToFilter);
e.printStackTrace(pw);
String sStackTrace = sw.toString(); 
System.out.println(sStackTrace);

Where the SelectivePrintWriter class is given by:

public class SelectivePrintWriter extends PrintWriter {
    private boolean on = true;
    private static final String AT = "\tat";
    private String internal;

    public SelectivePrintWriter(Writer out, String packageOrClassName) {
        super(out);
        internal = "\tat " + packageOrClassName;
    }

    public void println(Object obj) {
        if (obj instanceof String) {
            String txt = (String) obj;
            if (!txt.startsWith(AT)) on = true;
            else if (txt.startsWith(internal)) on = false;
            if (on) super.println(txt);
        } else {
            super.println(obj);
        }
    }
}

Please note this class may be easily adapted to filter out by Regex, contains or other criteria. Also note it depends upon Throwable implementation details (not likely to change, but still).

Sorting a list using Lambda/Linq to objects

You could use Reflection to get the value of the property.

list = list.OrderBy( x => TypeHelper.GetPropertyValue( x, sortBy ) )
           .ToList();

Where TypeHelper has a static method like:

public static class TypeHelper
{
    public static object GetPropertyValue( object obj, string name )
    {
        return obj == null ? null : obj.GetType()
                                       .GetProperty( name )
                                       .GetValue( obj, null );
    }
}

You might also want to look at Dynamic LINQ from the VS2008 Samples library. You could use the IEnumerable extension to cast the List as an IQueryable and then use the Dynamic link OrderBy extension.

 list = list.AsQueryable().OrderBy( sortBy + " " + sortDirection );

Sharing a variable between multiple different threads

In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

public class Test {
  class Control {
    public volatile boolean flag = false;
  }
  final Control control = new Control();

  class T1 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  class T2 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  private void test() {
    T1 main = new T1();
    T2 help = new T2();

    new Thread(main).start();
    new Thread(help).start();
  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Test test = new Test();
      test.test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

TypeError: Object of type 'bytes' is not JSON serializable

You are creating those bytes objects yourself:

item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)

Each of those t.encode(), l.encode() and d.encode() calls creates a bytes string. Do not do this, leave it to the JSON format to serialise these.

Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json module and the standard file object returned by the open() call to handle encoding.

You also don't need to convert your items list to a dictionary; it'll already be an object that can be JSON encoded directly:

class W3SchoolPipeline(object):    
    def __init__(self):
        self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(item) + '\n'
        self.file.write(line)
        return item

I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape') it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

How to delete a folder with files using Java

You can use FileUtils.deleteDirectory. JAVA can't delete the non-empty foldres with File.delete().

What is the best way to get the minimum or maximum value from an Array of numbers?

This depends on real world application requirements.

If your question is merely hypothetical, then the basics have already been explained. It is a typical search vs. sort problem. It has already been mentioned that algorithmically you are not going to achieve better than O(n) for that case.

However, if you are looking at practical use, things get more interesting. You would then need to consider how large the array is, and the processes involved in adding and removing from the data set. In these cases, it can be best to take the computational 'hit' at insertion / removal time by sorting on the fly. Insertions into a pre-sorted array are not that expensive.

The quickest query response to the Min Max request will always be from a sorted array, because as others have mentioned, you simply take the first or last element - giving you an O(1) cost.

For a bit more of a technical explanation on the computational costs involved, and Big O notation, check out the Wikipedia article here.

Nick.

Binding objects defined in code-behind

You can try x:Reference trick

<Window ... x:Name="myWindow"><ListBox ItemsSource="{Binding Items, Source={x:Reference myWindow}}" /></Window>

How do I get the AM/PM value from a DateTime?

@Andy's answer is Okay. But if you want to show time without 24 hours format then you may follow like this way

string dateTime = DateTime.Now.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture);

After that, you should get time like as "10:35:20 PM" or "10:35:20 AM"

CSS: how to add white space before element's content?

You can use the unicode of a non breaking space :

p:before { content: "\00a0 "; }

See JSfiddle demo

[style improved by @Jason Sperske]

How to write trycatch in R

R uses functions for implementing try-catch block:

The syntax somewhat looks like this:

result = tryCatch({
    expr
}, warning = function(warning_condition) {
    warning-handler-code
}, error = function(error_condition) {
    error-handler-code
}, finally={
    cleanup-code
})

In tryCatch() there are two ‘conditions’ that can be handled: ‘warnings’ and ‘errors’. The important thing to understand when writing each block of code is the state of execution and the scope. @source

How to get a complete list of ticker symbols from Yahoo Finance?

I have been researching this for a few days, following endless leads that got close, but not quite, to what I was after.

My need is for a simple list of 'symbol, sector, industry'. I'm working in Java and don't want to use any platform native code.

It seems that most other data, like quotes, etc., is readily available.

Finally, followed a suggestion to look at 'finviz.com'. Looks like just the ticket. Try using the following:

http://finviz.com/export.ashx?v=111&t=aapl,cat&o=ticker This comes back as lines, csv style, with a header row, ordered by ticker symbol. You can keep adding tickers. In code, you can read the stream. Or you can let the browser ask you whether to open or save the file.

http://finviz.com/export.ashx?v=111&&o=ticker Same csv style, but pulls all available symbols (a lot, across global exchanges)

Replace 'export' with 'screener' and the data will show up in the browser.

There are many more options you can use, one for every screener element on the site.

So far, this is the most powerful and convenient programmatic way to get the few pieces of data I couldn't otherwise seem to easily get. And, it looks like this site could well be a single source for most of what you might need other than real- or near-real-time quotes.

Calling a php function by onclick event

You cannot execute php functions from JavaScript.

PHP runs on the server before the browser sees it. PHP outputs HTML and JavaScript.

When the browser reads the html and javascript it executes it.

Can I nest a <button> element inside an <a> using HTML5?

_x000D_
_x000D_
<a href="index.html">_x000D_
  <button type="button">Submit</button>_x000D_
</a>
_x000D_
_x000D_
_x000D_ Or you can use java script in button as:

_x000D_
_x000D_
<button type="submit" onclick="myFunction()">Submit</button>_x000D_
<script>_x000D_
  function myFunction() {_x000D_
      var w = window.open(file:///E:/Aditya%20panchal/index.html);_x000D_
    }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I had the following configuration in my httpd.conf that denied executing the wpadmin/setup-config.php file from wordpress. Removing the |-config part solved the problem. I think this httpd.conf is from plesk but it could be some default suggested config from wordpress, i don't know. Anyway, I could safely add it back after the setup finished.

<LocationMatch "(?i:(?:wp-config\\.bak|\\.wp-config\\.php\\.swp|(?:readme|license|changelog|-config|-sample)\\.(?:php|md|txt|htm|html)))">
                        Require all denied
                </LocationMatch>

How to set selected value from Combobox?

I suspect something is not right when you are saving to the db. Do i understand your steps as:

  1. populate and bind
  2. user selects and item, hit and save.. then you save in the db
  3. now if you select another item it won't select?

got more code, especially when saving? where in your code are initializing and populating the bindinglist

How to convert HTML file to word?

A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.

SQL grouping by month and year

If I understand correctly. In order to group your results as requested, your Group By clause needs to have the same expression as your select statement.

GROUP BY MONTH(date) + '.' + YEAR(date)

To display the date as "month-date" format change the '.' to '-' The full syntax would be something like this.

SELECT MONTH(date) + '-' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS
SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY MONTH(date) + '.' + YEAR(date)

How to implement 2D vector array?

I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:

// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);

Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?

?: ?? Operators Instead Of IF|ELSE

the ?: is the itinerary operator. (believe i spelled that properly) and it's simple to use. as in a boolean predicate ? iftrue : ifalse; But you must have a rvalue/lvalue as in rvalue = predicate ? iftrue: iffalse;

ex int i = x < 7 ? x : 7;

if x was less than 7, i would get assigned x, if not i would be 7.

you can also use it in a return, as in return x < 7 ? x : 7;

again, as above , this would have the same affect.

so, Source = Source == value ? Source : string.Empty; i believe is what your trying to acheive.

Close dialog on click (anywhere)

This post may help:

http://www.jensbits.com/2010/06/16/jquery-modal-dialog-close-on-overlay-click/

See also How to close a jQuery UI modal dialog by clicking outside the area covered by the box? for explanation of when and how to apply overlay click or live event depending on how you are using dialog on page.

Fatal error: Call to undefined function curl_init()

Don't have enough reputation to comment yet. Using Ubuntu and a simple:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart

Did NOT work for me.

For some reason curl.so was installed in a location not picked up by default. I checked the extension_dir in my php.ini and copied over the curl.so to my extension_dir

cp /usr/lib/php5/20090626/curl.so  /usr/local/lib/php/extensions/no-debug-non-zts-20090626

Hope this helps someone, adjust your path locations accordingly.

How do I disable a href link in JavaScript?

you can deactivate all links in a page with this style class:

a {
    pointer-events:none;
}

now of course the trick is deactivate the links only when you need to, this is how to do it:

use an empty A class, like this:

a {}

then when you want to deactivate the links, do this:

    GetStyleClass('a').pointerEvents = "none"

    function GetStyleClass(className)
    {
       for (var i=0; i< document.styleSheets.length; i++) {
          var styleSheet = document.styleSheets[i]

          var rules = styleSheet.cssRules || styleSheet.rules

          for (var j=0; j<rules.length; j++) {
             var rule = rules[j]

             if (rule.selectorText === className) {
                return(rule.style)
             }
          }
       }

       return 0
    }

NOTE: CSS rule names are transformed to lower case in some browsers, and this code is case sensitive, so better use lower case class names for this

to reactivate links:

GetStyleClass('a').pointerEvents = ""

check this page http://caniuse.com/pointer-events for information about browser compatibility

i think this is the best way to do it, but sadly IE, like always, will not allow it :) i'm posting this anyway, because i think this contains information that can be useful, and because some projects use a know browser, like when you are using web views on mobile devices.

if you just want to deactivate ONE link (i only realize THAT was the question), i would use a function that manualy sets the url of the current page, or not, based on that condition. (like the solution you accepted)

this question was a LOT easier than i thought :)

Simple PHP form: Attachment to email (code golf)

In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.

As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.

With Zend_Mail, sending an email with an attachment is as simple as:

$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();

If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.

JavaScript post request like a form submit

Three options here.

  1. Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.

  2. Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in Using POST method in XMLHTTPRequest (Ajax).)

  3. Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.

How to convert String to long in Java?

Long.valueOf(String s) - obviously due care must be taken to protect against non-numbers if that is possible in your code.

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

Setting Java heap space under Maven 2 on Windows

The environment variable to set is MAVEN_OPTS, for example MAVEN_OPTS=-Xmx1024m. The maxmem configuration in the pom only applies when you set the compiler plugin to fork javac into a new JVM. Otherwise the plugin runs inside the same VM as Maven and thus within the memory passed on the command line via the MAVEN_OPTS.

To set MAVEN_OPTS under Windows 7:

  1. Right click on My Computer and select Properties (keyboard shortcut press Windows + Pause/Break)
  2. Click the Advanced System Settings link located in the left navigation of System Properties to display the Advanced System Properties
  3. Go to the Advanced tab and click the Environment Variables button located at the bottom of the Advanced System Properties configuration window
  4. Create a New user variable, set the Variable name to MAVEN_OPTS and set the Variable value to -Xmx1024m (or more)

Open a new command window and run mvn.

How to convert currentTimeMillis to a date in Java?

I do it like this:

static String formatDate(long dateInMillis) {
    Date date = new Date(dateInMillis);
    return DateFormat.getDateInstance().format(date);
}

You can also use getDateInstance(int style) with following parameters:

DateFormat.SHORT

DateFormat.MEDIUM

DateFormat.LONG

DateFormat.FULL

DateFormat.DEFAULT

Structure of a PDF file?

One way to get some clues is to create a PDF file consisting of a blank page. I have CutePDF Writer on my computer, and made a blank Wordpad document of one page. Printed to a .pdf file, and then opened the .pdf file using Notepad.

Next, use a copy of this file and eliminate lines or blocks of text that might be of interest, then reload in Acrobat Reader. You'd be surprised at how little information is needed to make a working one-page PDF document.

I'm trying to make up a spreadsheet to create a PDF form from code.

Invoke-WebRequest, POST with parameters

Single command without ps variables when using JSON as body {lastName:"doe"} for POST api call:

Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
                  -Method POST `
                  -Body (@{"lastName"="doe";}|ConvertTo-Json) `
                  -Uri https://api.dummy.com/getUsers `
                  -ContentType application/json

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

python - if not in list

Your code should work, but you can also try:

    if not item in mylist :

CSV API for Java

Reading CSV format description makes me feel that using 3rd party library would be less headache than writing it myself:

Wikipedia lists 10 or something known libraries:

I compared libs listed using some kind of check list. OpenCSV turned out a winner to me (YMMV) with the following results:

+ maven

+ maven - release version   // had some cryptic issues at _Hudson_ with snapshot references => prefer to be on a safe side

+ code examples

+ open source   // as in "can hack myself if needed"

+ understandable javadoc   // as opposed to eg javadocs of _genjava gj-csv_

+ compact API   // YAGNI (note *flatpack* seems to have much richer API than OpenCSV)

- reference to specification used   // I really like it when people can explain what they're doing

- reference to _RFC 4180_ support   // would qualify as simplest form of specification to me

- releases changelog   // absence is quite a pity, given how simple it'd be to get with maven-changes-plugin   // _flatpack_, for comparison, has quite helpful changelog

+ bug tracking

+ active   // as in "can submit a bug and expect a fixed release soon"

+ positive feedback   // Recommended By 51 users at sourceforge (as of now)

Remove legend ggplot 2.2

from r cookbook, where bp is your ggplot:

Remove legend for a particular aesthetic (fill):

bp + guides(fill=FALSE)

It can also be done when specifying the scale:

bp + scale_fill_discrete(guide=FALSE)

This removes all legends:

bp + theme(legend.position="none")

Media query to detect if device is touchscreen

Media types do not allow you to detect touch capabilities as part of the standard:

http://www.w3.org/TR/css3-mediaqueries/

So, there is no way to do it consistently via CSS or media queries, you will have to resort to JavaScript.

No need to use Modernizr, you can just use plain JavaScript:

<script type="text/javascript">
    var is_touch_device = 'ontouchstart' in document.documentElement;
    if(is_touch_device) alert("touch is enabled!");
</script>

urllib2 and json

Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.

import json
import urllib2
data = json.dumps([1, 2, 3])
clen = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()

Took me for ever to figure this out, so I hope it helps someone else.

Programmatically switching between tabs within Swift

If you want to do this from code that you are writing as part of a particular view controller, like in response to a button press or something, you can do this:

@IBAction func pushSearchButton(_ sender: UIButton?) {
    if let tabBarController = self.navigationController?.tabBarController  {
        tabBarController.selectedIndex = 1
    }
}

And you can also add code to handle tab switching using the UITabBarControllerDelegate methods. Using tags on the base view controllers of each tab, you can see where you are and act accordingly: For example

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
    // if we didn't change tabs, don't do anything
    if tabBarController.selectedViewController?.tabBarItem.tag ==  viewController.tabBarItem.tag {
        return false
    }
    
    if viewController.tabBarItem.tag == 4096 { // some particular tab
        // do stuff appropriate for a transition to this particular tab
    }
    else if viewController.tabBarItem.tag == 2048 { // some other tab
        // do stuff appropriate for a transition to this other tab
    }
}

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

An explanation of the following error:

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

Summary:

You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open(); inside of a loop, and forgot to run conn.close();. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:

protected void finalize() throws Throwable  
{  
    try { your_connection.close(); } 
    catch (SQLException e) { 
        e.printStackTrace();
    }
    super.finalize();  
}  

Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.

Run this SQL to see postgresql max connections allowed:

show max_connections;

The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.

Take a look at exactly who/what/when/where is holding open your connections:

SELECT * FROM pg_stat_activity;

The number of connections currently used is:

SELECT COUNT(*) from pg_stat_activity;

Debugging strategy

  1. You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.

  2. Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection, make sure every code line where you create a connection ends with a connection.close();

How to set the max_connections higher:

max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.

  1. First find your postgresql.conf file
  2. If you don't know where it is, query the database with the sql: SHOW config_file;
  3. Mine is in: /var/lib/pgsql/data/postgresql.conf
  4. Login as root and edit that file.
  5. Search for the string: "max_connections".
  6. You'll see a line that says max_connections=100.
  7. Set that number bigger, check the limit for your postgresql version.
  8. Restart the postgresql database for the changes to take effect.

What's the maximum max_connections?

Use this query:

select min_val, max_val from pg_settings where name='max_connections';

I get the value 8388607, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.

Get width height of remote image from url

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

else & elif statements not working in Python

elif and else must immediately follow the end of the if block, or Python will assume that the block has closed without them.

if 1:
    pass
             <--- this line must be indented at the same level as the `pass`
else:
    pass

In your code, the interpreter finishes the if block when the indentation, so the elif and the else aren't associated with it. They are thus being understood as standalone statements, which doesn't make sense.


In general, try to follow the style guidelines, which include removing excessive whitespace.

How do I generate random integers within a specific range in Java?

You can achieve that concisely in Java 8:

Random random = new Random();

int max = 10;
int min = 5;
int totalNumber = 10;

IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);

Confused about stdin, stdout and stderr?

I'm afraid your understanding is completely backwards. :)

Think of "standard in", "standard out", and "standard error" from the program's perspective, not from the kernel's perspective.

When a program needs to print output, it normally prints to "standard out". A program typically prints output to standard out with printf, which prints ONLY to standard out.

When a program needs to print error information (not necessarily exceptions, those are a programming-language construct, imposed at a much higher level), it normally prints to "standard error". It normally does so with fprintf, which accepts a file stream to use when printing. The file stream could be any file opened for writing: standard out, standard error, or any other file that has been opened with fopen or fdopen.

"standard in" is used when the file needs to read input, using fread or fgets, or getchar.

Any of these files can be easily redirected from the shell, like this:

cat /etc/passwd > /tmp/out     # redirect cat's standard out to /tmp/foo
cat /nonexistant 2> /tmp/err   # redirect cat's standard error to /tmp/error
cat < /etc/passwd              # redirect cat's standard input to /etc/passwd

Or, the whole enchilada:

cat < /etc/passwd > /tmp/out 2> /tmp/err

There are two important caveats: First, "standard in", "standard out", and "standard error" are just a convention. They are a very strong convention, but it's all just an agreement that it is very nice to be able to run programs like this: grep echo /etc/services | awk '{print $2;}' | sort and have the standard outputs of each program hooked into the standard input of the next program in the pipeline.

Second, I've given the standard ISO C functions for working with file streams (FILE * objects) -- at the kernel level, it is all file descriptors (int references to the file table) and much lower-level operations like read and write, which do not do the happy buffering of the ISO C functions. I figured to keep it simple and use the easier functions, but I thought all the same you should know the alternatives. :)

New line character in VB.Net?

Environment.NewLine or vbCrLf or Constants.vbCrLf

More information about VB.NET new line:

http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

jQuery get text as number

Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)

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

Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.

How to assign name for a screen?

To create a new screen with the name foo, use

screen -S foo

Then to reattach it, run

screen -r foo  # or use -x, as in
screen -x foo  # for "Multi display mode" (see the man page)

Running a Python script from PHP

To clarify which command to use based on the situation

exec() - Execute an external program

system() - Execute an external program and display the output

passthru() - Execute an external program and display raw output

Source: http://php.net/manual/en/function.exec.php

Remove pandas rows with duplicate indices

I would suggest using the duplicated method on the Pandas Index itself:

df3 = df3[~df3.index.duplicated(keep='first')]

While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.

Using the sample data provided:

>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop

>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop

>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop

Note that you can keep the last element by changing the keep argument to 'last'.

It should also be noted that this method works with MultiIndex as well (using df1 as specified in Paul's example):

>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop

>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop

How can I dynamically add items to a Java array?

Use an ArrayList or juggle to arrays to auto increment the array size.

How to determine when a Git branch was created?

Pro Git § 3.1 Git Branching - What a Branch Is has a good explanation of what a git branch really is

A branch in Git is simply a lightweight movable pointer to [a] commit.

Since a branch is just a lightweight pointer, git has no explicit notion of its history or creation date. "But hang on," I hear you say, "of course git knows my branch history!" Well, sort of.

If you run either of the following:

git log <branch> --not master
gitk <branch> --not master

you will see what looks like the "history of your branch", but is really a list of commits reachable from 'branch' that are not reachable from master. This gives you the information you want, but if and only if you have never merged 'branch' back to master, and have never merged master into 'branch' since you created it. If you have merged, then this history of differences will collapse.

Fortunately the reflog often contains the information you want, as explained in various other answers here. Use this:

git reflog --date=local <branch>

to show the history of the branch. The last entry in this list is (probably) the point at which you created the branch.

If the branch has been deleted then 'branch' is no longer a valid git identifier, but you can use this instead, which may find what you want:

git reflog --date=local | grep <branch>

Or in a Windows cmd shell:

git reflog --date=local | find "<branch>"

Note that reflog won't work effectively on remote branches, only ones you have worked on locally.

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Delete package.json and package-lock.json file

Then type npm init

after that type npm install socket.io --save

finally type npm install

It works for me

Attach parameter to button.addTarget action in Swift

For Swift 3.0 you can use following

button.addTarget(self, action: #selector(YourViewController.YourMethodName(_:)), for:.touchUpInside)

func YourMethodName(_ sender : UIButton) {
    print(sender.tag)

}

Check if value exists in enum in TypeScript

export enum UserLevel {
  Staff = 0,
  Leader,
  Manager,
}

export enum Gender {
  None = "none",
  Male = "male",
  Female = "female",
}

Difference result in log:

log(Object.keys(Gender))
=>
[ 'None', 'Male', 'Female' ]

log(Object.keys(UserLevel))
=>
[ '0', '1', '2', 'Staff', 'Leader', 'Manager' ]

The solution, we need to remove key as a number.

export class Util {
  static existValueInEnum(type: any, value: any): boolean {
    return Object.keys(type).filter(k => isNaN(Number(k))).filter(k => type[k] === value).length > 0;
  }
}

Usage

// For string value
if (!Util.existValueInEnum(Gender, "XYZ")) {
  //todo
}

//For number value, remember cast to Number using Number(val)
if (!Util.existValueInEnum(UserLevel, 0)) {
  //todo
}

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

How do I disable a Button in Flutter?

According to the docs:

"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."

https://docs.flutter.io/flutter/material/RaisedButton-class.html

So, you might do something like this:

    RaisedButton(
      onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
      child: Text('Button text')
    );

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

Include of non-modular header inside framework module

I solved it removing Modules folder from the framework.

  • Browse to your framework location which is present in the App Project using finder

  • Go inside Test.framework folder (In the above case it will be CoreLibrary.framework) & Delete Modules folder.

  • Clean and Re Build the app, it will solve the problem.

How do I use jQuery to redirect?

This is a shorthand Ajax function, which is equivalent to:

$.ajax({  type: "POST",
           url: url,  
          data: { username: value_login.val(), firstname: value_firstname.val(), 
                  lastname: value_lastname.val(), email: value_email.val(),
                  password: value_password.val()
                },
          dataType: "json"
       success: success// -> call your func here  
      });

Hope This helps

Oracle SQL escape character (for a '&')

The real answer is you need to set the escape character to '\': SET ESCAPE ON

The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.


None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.

How to specify a multi-line shell variable?

Thanks to dimo414's answer to a similar question, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

How can I access Oracle from Python?

Ensure these two and it should work:-

  1. Python, Oracle instantclient and cx_Oracle are 32 bit.
  2. Set the environment variables.

Fixes this issue on windows like a charm.

Set Google Maps Container DIV width and height 100%

Gmap writes inline style position to relative to the div. Overwrite that with :

google.maps.event.addListener(map, 'tilesloaded', function(){
    document.getElementById('maps').style.position = 'static';
    document.getElementById('maps').style.background = 'none';
});

Hope it helps.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

Adapted from Timmmm to PYQT5

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel


class Label(QLabel):

    def __init__(self):
        super(Label, self).__init__()
        self.pixmap_width: int = 1
        self.pixmapHeight: int = 1

    def setPixmap(self, pm: QPixmap) -> None:
        self.pixmap_width = pm.width()
        self.pixmapHeight = pm.height()

        self.updateMargins()
        super(Label, self).setPixmap(pm)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        self.updateMargins()
        super(Label, self).resizeEvent(a0)

    def updateMargins(self):
        if self.pixmap() is None:
            return
        pixmapWidth = self.pixmap().width()
        pixmapHeight = self.pixmap().height()
        if pixmapWidth <= 0 or pixmapHeight <= 0:
            return
        w, h = self.width(), self.height()
        if w <= 0 or h <= 0:
            return

        if w * pixmapHeight > h * pixmapWidth:
            m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
            self.setContentsMargins(m, 0, m, 0)
        else:
            m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
            self.setContentsMargins(0, m, 0, m)

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

How to refer environment variable in POM.xml?

I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.

Using ${env.foo} or ${env.FOO} didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:

  1. Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh to call it from the parent script.

  2. In shared-pom, create a command-line param that grabs the environment variable:

<plugin>
  ...
  <executions>
    <executions>
    ...
      <execution>
      ...
        <configuration>
          <param>${foo}</param> <!-- Note this is *not* ${env.foo} -->
        </configuration>
  1. In com.google.code.maven-replacer-plugin, make the replacement value ${foo}.

  2. In my shell script that calls maven, add this to the command: -Dfoo=$foo

Inserting data into a MySQL table using VB.NET

Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean

Private Sub Insert_Car()

Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@car_id,@member_id,@model,@color,@chassis_id,@plate_number,@code)"

Dim cmd = new MySqlCommand(sql, conn)

    cmd.Paramaters.AddwithValue("@car_id", txtCar.Text)
    cmd.Paramaters.AddwithValue("@member_id", txtMember.Text)
    cmd.Paramaters.AddwithValue("@model", txtModel.Text)
    cmd.Paramaters.AddwithValue("@color", txtColor.Text)
    cmd.Paramaters.AddwithValue("@chassis_id", txtChassis.Text)
    cmd.Paramaters.AddwithValue("@plate_number", txtPlateNo.Text)
    cmd.Paramaters.AddwithValue("@code", txtCode.Text)

    Try
        conn.Open()
        If cmd.ExecuteNonQuery() > 0 Then
            ireturn = True
        End If  
        conn.Close()


    Catch ex as Exception
        ireturn = False
        conn.Close()
    End Try

Return ireturn

End Sub

SQL Error: ORA-00942 table or view does not exist

I am using Oracle Database and i had same problem. Eventually i found ORACLE DB is converting all the metadata (table/sp/view/trigger) in upper case.

And i was trying how i wrote table name (myTempTable) in sql whereas it expect how it store table name in databsae (MYTEMPTABLE). Also same applicable on column name.

It is quite common problem with developer whoever used sql and now jumped into ORACLE DB.

How to set a cell to NaN in a pandas dataframe

just use replace:

In [106]:
df.replace('N/A',np.NaN)

Out[106]:
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

What you're trying is called chain indexing: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

You can use loc to ensure you operate on the original dF:

In [108]:
df.loc[df['y'] == 'N/A','y'] = np.nan
df

Out[108]:
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

Count characters in textarea

Seems like the most reusable and elegant solution combines the abive to take MaxLength from the Input attribute and then reference the Span element with a predictable id....

Then to use, all you need to do is add '.countit' to the Input class and 'counter_' + [input-ID] to your span

HTML

<textarea class="countit" name="name" maxlength='6' id="post"></textarea>
<span>characters remaining: <span id="counter_name"></span></span>
<br>
<textarea class="countit" name="post" maxlength='20' id="post"></textarea>
<span>characters remaining: <span id="counter_post"></span></span>
<br>
<textarea class="countit" name="desc" maxlength='10' id="desc"></textarea>
<span>characters remaining: <span id="counter_desc"></span></span>

Jquery

$(".countit").keyup(function () {
  var maxlength = $(this).attr("maxlength");
  var currentLength = $(this).val().length;

  if( currentLength >= maxlength ){
    $("#counter_" + $(this).attr("id")).html(currentLength + ' / ' + maxlength);
    }else{
    $("#counter_" + $(this).attr("id")).html(maxlength - currentLength + " chars left");
  }
});

Get values from a listbox on a sheet

Take selected value:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)

Reverse ip, find domain names on ip address

You can use nslookup on the IP. Reverse DNS is defined with the .in-addr.arpa domain.

Example:

nslookup somedomain.com

yields 123.21.2.3, and then you do:

nslookup 123.21.2.3

this will ask 3.2.21.123.in-addr.arpa and yield the domain name (if there is one defined for reverse DNS).

Elegant Python function to convert CamelCase to snake_case?

stringcase is my go-to library for this; e.g.:

>>> from stringcase import pascalcase, snakecase
>>> snakecase('FooBarBaz')
'foo_bar_baz'
>>> pascalcase('foo_bar_baz')
'FooBarBaz'

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Template/HTML File (component.ts)

<select>
 <option *ngFor="let v of values" [value]="v" (ngModelChange)="onChange($event)">  
    {{v.name}}
  </option>
</select>

Typescript File (component.ts)

values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

onChange(cityEvent){
    console.log(cityEvent); // It will display the select city data
}

(ngModelChange) is the @Output of the ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive

How can I get input radio elements to horizontally align?

To get your radio button to list horizontally , just add

RepeatDirection="Horizontal"

to your .aspx file where the asp:radiobuttonlist is being declared.

What is object slicing?

I see all the answers mention when object slicing happens when data members are sliced. Here I give an example that the methods are not overridden:

class A{
public:
    virtual void Say(){
        std::cout<<"I am A"<<std::endl;
    }
};

class B: public A{
public:
    void Say() override{
        std::cout<<"I am B"<<std::endl;
    }
};

int main(){
   B b;
   A a1;
   A a2=b;

   b.Say(); // I am B
   a1.Say(); // I am A
   a2.Say(); // I am A   why???
}

B (object b) is derived from A (object a1 and a2). b and a1, as we expect, call their member function. But from polymorphism viewpoint we don’t expect a2, which is assigned by b, to not be overridden. Basically, a2 only saves A-class part of b and that is object slicing in C++.

To solve this problem, a reference or pointer should be used

 A& a2=b;
 a2.Say(); // I am B

or

A* a2 = &b;
a2->Say(); // I am B

For more details see my post

How to escape double quotes in a title attribute

It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>") and the title was <a href=".." title="Test&quot; &lt;br&gt; &lt;p&gt;">Testing</a>.

It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>") and it worked in every browser.

Android set bitmap to Imageview

There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.

Examples:

  1. Load URL into ImageView without generating a bitmap:

    Picasso.with(context) // Context
           .load("http://abc.imgur.com/gxsg.png") // URL or file
           .into(imageView); // An ImageView object to show the loaded image
    
  2. Load URL into ImageView by generating a bitmap:

    Picasso.with(this)
           .load(artistImageUrl)
           .into(new Target() {
               @Override
               public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                   /* Save the bitmap or do something with it here */
    
                   // Set it in the ImageView
                   theView.setImageBitmap(bitmap)
               }
    
               @Override
               public void onBitmapFailed(Drawable errorDrawable) {
    
               }
    
               @Override
               public void onPrepareLoad(Drawable placeHolderDrawable) {
    
               }
           });
    

There are many more options available in Picasso. Here is the documentation.

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

Why is the Android emulator so slow? How can we speed up the Android emulator?

Using the ADB utility I've discovered some more information that is important.

The emulator is actually running, but it seems like the graphical interface may be the problem.

When the Android splash screen is up and you are waiting forever it looks like the following: enter image description here

The emulator is actually running because you can run the following command-line tool and see the listed processes:

adb -s emulator-5554 shell ps 

That will provide you with a list of processes which are running on the device, which seems stuck.

I piped the output to a file and here is a list of all the running processes:

USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME

root      1     0     696    500   c02ae25a 0805a406 S /init
root      2     0     0      0     c02315a2 00000000 S kthreadd
root      3     2     0      0     c021f9dc 00000000 S ksoftirqd/0
root      5     2     0      0     c022e8d7 00000000 S kworker/u:0
root      6     2     0      0     c022e085 00000000 S khelper
root      7     2     0      0     c022e8d7 00000000 S kworker/u:1
root      255   2     0      0     c02886de 00000000 S sync_supers
root      257   2     0      0     c028935e 00000000 S bdi-default
root      259   2     0      0     c022e085 00000000 S kblockd
root      267   2     0      0     c022e085 00000000 S ata_sff
root      278   2     0      0     c04f610f 00000000 S khubd
root      283   2     0      0     c022e085 00000000 S md
root      297   2     0      0     c022e085 00000000 S cfg80211
root      298   2     0      0     c022e8d7 00000000 S kworker/0:1
root      413   2     0      0     c0283057 00000000 S kswapd0
root      481   2     0      0     c02cd713 00000000 S fsnotify_mark
root      501   2     0      0     c022e085 00000000 S crypto
root      590   2     0      0     c022e085 00000000 S iscsi_eh
root      611   2     0      0     c048aa21 00000000 S mtdblock0
root      619   2     0      0     c048aa21 00000000 S mtdblock1
root      627   2     0      0     c048aa21 00000000 S mtdblock2
root      666   2     0      0     c022e8d7 00000000 S kworker/0:2
root      700   2     0      0     c022e085 00000000 S binder
root      724   2     0      0     c022e085 00000000 S deferwq
root      725   1     624    348   c02ae25a 0805a406 S /sbin/ueventd
root      932   2     0      0     c055236e 00000000 S mmcqd/0
root      939   2     0      0     c0340f30 00000000 S yaffs-bg-1
root      941   2     0      0     c0340f30 00000000 S yaffs-bg-1
root      942   2     0      0     c0340f30 00000000 S yaffs-bg-1
system    943   1     1340   400   c056a35d b76a1eb6 S /system/bin/servicemanager
root      944   1     5540   924   ffffffff b7646c11 S /system/bin/vold
root      947   1     1548   504   c05785ce b766c163 S /system/bin/debuggerd
radio     948   1     6420   1016  ffffffff b76d3c11 S /system/bin/rild
system    949   1     20088  2876  ffffffff b7655eb6 S /system/bin/surfaceflinger
drm       951   1     10480  2920  ffffffff b7585eb6 S /system/bin/drmserver
keystore  954   1     5036   1416  c056a35d b765deb6 S /system/bin/keystore
root      955   1     1324   440   c02d0083 b76b28ab S /system/bin/qemud
shell     958   1     1428   668   c03e9ad9 b767fa76 S /system/bin/sh
root      959   1     4680   304   ffffffff 08063530 S /sbin/adbd
graphics  1012  1     17980  4276  ffffffff b7652eb6 S /system/bin/bootanimation
media     4743  1     25288  6232  ffffffff b75beeb6 S /system/bin/mediaserver
root      4744  1     3944   1164  00000000 b7628976 R /system/bin/netd
root      4770  4744  0      0     c021de78 00000000 Z iptables
root      4771  959   1768   540   00000000 b766fa76 R ps

For fun I then ran the following command and killed the "Android" animation:

adb -s emulator-5554 shell kill 1012

The splash screen became blank so something is really happening.

I tried and succeeded at killing some other processes and that made me feel good but the emulator still didn't ever seem to start. Oh well. I'm running a QuadCore i7 with 8Gb of ram. Also running the haxm with the settings described in other posts in this question.

Note: I'm updating this on 09/19/2014 - I learned that this odd behavior where the emulator would attempt to start the instance but never would was all related to the file rights on the emulator files. They were set to read-only because of the way they were copied, so the emulator attempts to install and write to its "virtual disk" but it's "virtual disk" is really a file or set of files which my OS has set to read-only and so it fails. These failures cause the emulator to never start. I set the files to full access and the emulator starts up in record time.

How to get values from IGrouping

Since IGrouping<TKey, TElement> implements IEnumerable<TElement>, you can use SelectMany to put all the IEnumerables back into one IEnumerable all together:

List<smth> list = new List<smth>();
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
IEnumerable<smth> smths = groups.SelectMany(group => group);
List<smth> newList = smths.ToList();

Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP

Video commentary of this solution: https://youtu.be/6BsU1n1KTdo

Why should C++ programmers minimize use of 'new'?

I think the poster meant to say You do not have to allocate everything on theheap rather than the the stack.

Basically objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.