Programs & Examples On #Text styling

Vertical (rotated) text in HTML table

Here is one that works for plain-text with some server side processing:

public string RotateHtmltext(string innerHtml)
{
   const string TRANSFORMTEXT = "transform: rotate(90deg);";
   const string EXTRASTYLECSS = "<style type='text/css'>.r90 {"
                                 + "-webkit-" + TRANSFORMTEXT
                                 + "-moz-" + TRANSFORMTEXT
                                 + "-o-" + TRANSFORMTEXT
                                 + "-ms-" + TRANSFORMTEXT
                                 + "" + TRANSFORMTEXT
                                 + "width:1em;line-height:1ex}</style>";
   const string WRAPPERDIV = "<div style='display: table-cell; vertical-align: middle;'>";

   var newinnerHtml = string.Join("</div>"+WRAPPERDIV, Regex.Split(innerHtml, @"<br */?>").Reverse());

   newinnerHtml = Regex.Replace(newinnerHtml, @"((?:<[^>]*>)|(?:[^<]+))",
                                 match => match.Groups[1].Value.StartsWith("<")
                                             ? match.Groups[1].Value
                                             : string.Join("", match.Groups[1].Value.ToCharArray().Select(x=>"<div class='r90'>"+x+"</div>")),
                                 RegexOptions.Singleline);
   return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + "</div>";
}

which gives something like:

<style type="text/css">.r90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
width: 1em;
line-height: 1ex; 
}</style>
<div style="display: table-cell; vertical-align: middle;">
<div class="r90">p</div>
<div class="r90">o</div>
<div class="r90">s</div>
</div><div style="display: table-cell; vertical-align: middle;">
<div class="r90">(</div>
<div class="r90">A</div>
<div class="r90">b</div>
<div class="r90">s</div>
<div class="r90">)</div>
</div>

http://jsfiddle.net/TzzHy/

How to set the font style to bold, italic and underlined in an Android TextView?

Or just like this in Kotlin:

val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG

Or in Java:

TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);

Keep it simple and in one line :)

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

Maybe you can refer to : http://msdn.microsoft.com/en-us/library/ms731364.aspx My solution is to change 2 properties authenticationScheme and proxyAuthenticationScheme to "Ntlm", and then it works.

PS: My environment is as follow - Server side: .net 2.0 ASMX - Client side: .net 4

Perform a Shapiro-Wilk Normality Test

Set the data as a vector and then place in the function.

Serializing PHP object to JSON

Just implement an Interface given by PHP JsonSerializable.

How can I introduce multiple conditions in LIKE operator?

select * from tbl where col like 'ABC%'
or col like 'XYZ%'
or col like 'PQR%';

This works in toad and powerbuilder. Don't know about the rest

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

CXF: No message body writer found for class - automatically mapping non-simple resources

In my scenario, i faced similar error, when the rest url without port number is not properly configured for load balancing. I verified the rest url with portnumber and this issue was not occurring. so we had to update the load balancing configuration to resolve this issue.

Difference between web reference and service reference?

A Web Reference allows you to communicate with any service based on any technology that implements the WS-I Basic Profile 1.1, and exposes the relevant metadata as WSDL. Internally, it uses the ASMX communication stack on the client's side.

A Service Reference allows you to communicate with any service based on any technology that implements any of the many protocols supported by WCF (including but not limited to WS-I Basic Profile). Internally, it uses the WCF communication stack on the client side.

Note that both these definitions are quite wide, and both include services not written in .NET.

It is perfectly possible (though not recommended) to add a Web Reference that points to a WCF service, as long as the WCF endpoint uses basicHttpBinding or some compatible custom variant.

It is also possible to add a Service Reference that points to an ASMX service. When writing new code, you should always use a Service Reference simply because it is more flexible and future-proof.

How to check if memcache or memcached is installed for PHP?

I combined, minified and extended (some more checks) the answers from @Bijay Rungta and @J.C. Inacio

<?php
if(!extension_loaded('Memcache'))
{
    die("Memcache extension is not loaded");
}

if (!class_exists('Memcache')) 
{
    die('Memcache class not available');
}

$memcacheObj = new Memcache;
if(!$memcacheObj)
{
    die('Could not create memcache object');
}

if (!$memcacheObj->connect('localhost')) 
{
    die('Could not connect to memcache server');
}

// testdata to store in memcache
$testData = array(
    'the' => 'cake',
    'is' => 'a lie',
);

// set data (if not present)
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    if(!$memcacheObj->set('data', $testData, 0, 300))
    {
        die('Memcache could not set the data');
    }
}

// try to fetch data
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    die('Memcache is not responding with data');
}

if($aData !== $testData)
{
    die('Memcache is responding but with wrong data');
}

die('Memcache is working fine');

textarea character limit

... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...

It ought to work.

How to check whether an object has certain method/property?

via Reflection

 var property = object.GetType().GetProperty("YourProperty")
 property.SetValue(object,some_value,null);

Similar is for methods

Solving Quadratic Equation

Below is the Program to Solve Quadratic Equation.

For Example: Solve x2 + 3x – 4 = 0

This quadratic happens to factor:

x2 + 3x – 4 = (x + 4)(x – 1) = 0

we already know that the solutions are x = –4 and x = 1.

enter image description here

    # import complex math module
    import cmath

    a = 1
    b = 5
    c = 6

    # To take coefficient input from the users
    # a = float(input('Enter a: '))
    # b = float(input('Enter b: '))
    # c = float(input('Enter c: '))

    # calculate the discriminant
    d = (b**2) - (4*a*c)

    # find two solutions
    sol1 = (-b-cmath.sqrt(d))/(2*a)
    sol2 = (-b+cmath.sqrt(d))/(2*a)

    print('The solution are {0} and {1}'.format(sol1,sol2))

Source: Python Program to Solve Quadratic Equation

How do I efficiently iterate over each entry in a Java Map?

Map<String, String> map = 
for (Map.Entry<String, String> entry : map.entrySet()) {
    MapKey = entry.getKey() 
    MapValue = entry.getValue();
}

ElasticSearch - Return Unique Values

Elasticsearch 1.1+ has the Cardinality Aggregation which will give you a unique count

Note that it is actually an approximation and accuracy may diminish with high-cardinality datasets, but it's generally pretty accurate in my testing.

You can also tune the accuracy with the precision_threshold parameter. The trade-off, or course, is memory usage.

This graph from the docs shows how a higher precision_threshold leads to much more accurate results.


Relative error vs threshold

Could not load file or assembly 'System.Data.SQLite'

This is an old post, but it may help some people searching on this error to try setting "Enable 32-Bit Applications" to True for the app pool. That is what resolved the error for me. I came upon this solution by reading some the comments to @beckelmw's answer.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

C#: New line and tab characters in strings

    StringBuilder SqlScript = new StringBuilder();

    foreach (var file in lstScripts)
    {
        var input = File.ReadAllText(file.FilePath);
        SqlScript.AppendFormat(input, Environment.NewLine);
    }

http://afzal-gujrat.blogspot.com/

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

How to use a ViewBag to create a dropdownlist?

Try:

In the controller:

ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");

In the View:

@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })

or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".

What is the 'new' keyword in JavaScript?

JavaScript is an object-oriented programming language and it's used exactly for creating instances. It's prototype-based, rather than class-based, but that does not mean that it is not object-oriented.

Requested registry access is not allowed

You Could Do The same as abatishchev but without the UAC

<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
   <security>
    <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

Difference between View and ViewGroup in Android

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box which responds to user inputs. Eg: EditText, Button, CheckBox, etc..

ViewGroup is a invisible container of other views (child views) and other viewgroups. Eg: LinearLayout is a viewgroup which can contain other views in it.

ViewGroup is a special kind of view which is extended from View as its base class. ViewGroup is the base class for layouts.

as name states View is singular and the group of Views is the ViewGroup.

more info: http://www.herongyang.com/Android/View-ViewGroup-Layout-and-Widget.html

How to get the user input in Java?

Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:

myScanner.close();

Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)

Deleting an element from an array in PHP

If the index is specified:

$arr = ['a', 'b', 'c'];
$index = 0;    
unset($arr[$index]);  // $arr = ['b', 'c']

If the index is NOT specified:

$arr = ['a', 'b', 'c'];
$index = array_search('a', $arr); // search the value to find index
if($index !== false){
   unset($arr[$index]);  // $arr = ['b', 'c']
}

The if condition is necessary because if index is not found, unset() will automatically delete the first element of the array which is not what we want.

Jackson overcoming underscores in favor of camel-case

Annotating all model classes looks to me as an overkill and Kenny's answer didn't work for me https://stackoverflow.com/a/43271115/4437153. The result of serialization was still camel case.

I realised that there is a problem with my spring configuration, so I had to tackle that problem from another side. Hopefully someone finds it useful, but if I'm doing something against springs' rules then please let me know.

Solution for Spring MVC 5.2.5 and Jackson 2.11.2

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);           

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
    }
}

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

<properties>
    <javac.src.version>1.8</javac.src.version>
    <javac.target.version>1.8</javac.target.version>
</properties>

It should be the same thing of maven.compiler.source/maven.compiler.target but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

Compare a string using sh shell

-eq is a mathematical comparison operator. I've never used it for string comparison, relying on == and != for compares.

if [ 'XYZ' == 'ABC' ]; then   # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
  echo "Match"
else
  echo "No Match"
fi

Boxplot in R showing the mean

I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.

Here is a small ETF portfolio example.

library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)

VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))


VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
                       quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                       compression = "m", retclass = c("zoo"))

TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                        compression = "m", retclass = c("zoo"))

TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
                         quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01", 
                         compression = "m", retclass = c("zoo"))

index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))

index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))

Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices, 
           TLT.prices, TIP.prices)

colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")

returnscc.z = diff(log(Prices.z))

start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z) 
head(returnscc.z)

Return Matrix

ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)

Box Plot of Return Matrix

chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
          mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
          element.color = "darkgray", outlier.symbol = 20, 
          xlab="Continuously Compounded Returns", sort.ascending=F)

You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)

Android Intent Cannot resolve constructor

this work for me

    ncharacters.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent openncharacter = new Intent(getApplicationContext(),ncharacters.class);
            startActivity(openncharacter);
        }
    });

og:type and valid values : constantly being parsed as og:type=website

I know this is an old one but it comes up top of Google and all the links provided now seem out of date.

This is the latest list of types Facebook accepts: https://developers.facebook.com/docs/reference/opengraph

If you don't use one of these then the type will default to 'website' which is best used for home pages/summarising a web site.

In answer to the OP you would now want to use a place which will allow you to add lat/long location details.

Python convert csv to xlsx

First install openpyxl:

pip install openpyxl

Then:

from openpyxl import Workbook
import csv


wb = Workbook()
ws = wb.active
with open('test.csv', 'r') as f:
    for row in csv.reader(f):
        ws.append(row)
wb.save('name.xlsx')

Using a different font with twitter bootstrap

you can customize twitter bootstrap css file, open the bootstrap.css file on a text editor, and change the font-family with your font name and SAVE it.

OR got to http://getbootstrap.com/customize/ and make a customized twitter bootstrap

How to URL encode a string in Ruby

I created a gem to make URI encoding stuff cleaner to use in your code. It takes care of binary encoding for you.

Run gem install uri-handler, then use:

require 'uri-handler'

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".to_uri
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

It adds the URI conversion functionality into the String class. You can also pass it an argument with the optional encoding string you would like to use. By default it sets to encoding 'binary' if the straight UTF-8 encoding fails.

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

Return current date plus 7 days

echo date('d-m-Y', strtotime('+7 days'));

Detect if Android device has Internet connection

If all above answers get you FATAL EXCEPTIONs like android.os.NetworkOnMainThreadException, this answer will really help you.
Because I got this error while trying to implement this.

The reason for this error is that the Network related codes cannot be on the main thread.
So, you need to create a new Thread as I shown below:

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
    try  {
        //Your code goes here
    } catch (Exception e) {
        e.printStackTrace();
    }
}});


And put your code in the place I commented.

Command line to remove an environment variable from the OS level configuration

I agree with CupawnTae.

SET is not useful for changes to the master environment.

FYI: System variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (a good deal longer than user vars).

The full command for a system var named FOOBAR therefore is:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

(Note the quotes required to handle the space.)

It is too bad the setx command doesn't support a delete syntax. :(

PS: Use responsibly - If you kill your path variable, don't blame me!

Android Studio suddenly cannot resolve symbols

I have finally figured out what causes this issue.

Actually, you should avoid pushing .idea/libraries folder to your repository. It creates weird stuff in Android Studio which tends to remove all downloaded libraries.

If you have commit history, just recreate all missing library files and avoid them to be committed again. Otherwise, just remove whole .idea folder and reimport it into AS.

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
  $username = $_POST['username']; $password = $_POST['password'];
  if($username === 'admin' && $password === 'password'){
    $_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
  }
  if($username !== 'admin')$userError = 'Invalid Username';
  if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <style type='text.css'>
       @import common.css;
     </style>
   </head>
<body>
  <form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
    <label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
    <div class='error'><?php echo $userError;?></div>
    <label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
    <div class='error'><?php echo $passError;?></div>
    <input type='submit' value='Home' name='sub' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

how do I make a single legend for many subplots with matplotlib?

While rather late to the game, I'll give another solution here as this is still one of the first links to show up on google. Using matplotlib 2.2.2, this can be achieved using the gridspec feature. In the example below the aim is to have four subplots arranged in a 2x2 fashion with the legend shown at the bottom. A 'faux' axis is created at the bottom to place the legend in a fixed spot. The 'faux' axis is then turned off so only the legend shows. Result: https://i.stack.imgur.com/5LUWM.png.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

#Gridspec demo
fig = plt.figure()
fig.set_size_inches(8,9)
fig.set_dpi(100)

rows   = 17 #the larger the number here, the smaller the spacing around the legend
start1 = 0
end1   = int((rows-1)/2)
start2 = end1
end2   = int(rows-1)

gspec = gridspec.GridSpec(ncols=4, nrows=rows)

axes = []
axes.append(fig.add_subplot(gspec[start1:end1,0:2]))
axes.append(fig.add_subplot(gspec[start2:end2,0:2]))
axes.append(fig.add_subplot(gspec[start1:end1,2:4]))
axes.append(fig.add_subplot(gspec[start2:end2,2:4]))
axes.append(fig.add_subplot(gspec[end2,0:4]))

line, = axes[0].plot([0,1],[0,1],'b')           #add some data
axes[-1].legend((line,),('Test',),loc='center') #create legend on bottommost axis
axes[-1].set_axis_off()                         #don't show bottommost axis

fig.tight_layout()
plt.show()

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

tr -d "\r" < file

take a look here for examples using sed:

# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format.
sed 's/.$//'               # assumes that all lines end with CR/LF
sed 's/^M$//'              # in bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//'            # works on ssed, gsed 3.02.80 or higher

# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format.
sed "s/$/`echo -e \\\r`/"            # command line under ksh
sed 's/$'"/`echo \\\r`/"             # command line under bash
sed "s/$/`echo \\\r`/"               # command line under zsh
sed 's/$/\r/'                        # gsed 3.02.80 or higher

Use sed -i for in-place conversion e.g. sed -i 's/..../' file.

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

Does java have a int.tryparse that doesn't throw an exception for bad data?

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

Syntax for creating a two-dimensional array in Java

Try:

int[][] multD = new int[5][10];

Note that in your code only the first line of the 2D array is initialized to 0. Line 2 to 5 don't even exist. If you try to print them you'll get null for everyone of them.

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

How to fetch all Git branches

We can put all branch or tag names in a temporary file, then do git pull for each name/tag:

git branch -r | grep origin | grep -v HEAD| awk -F/ '{print $NF}' > /tmp/all.txt
git tag -l >> /tmp/all.txt
for tag_or_branch in `cat /tmp/all.txt`; do git checkout $tag_or_branch; git pull origin $tag_or_branch; done

Identifying and removing null characters in UNIX

I’d use tr:

tr < file-with-nulls -d '\000' > file-without-nulls

If you are wondering if input redirection in the middle of the command arguments works, it does. Most shells will recognize and deal with I/O redirection (<, >, …) anywhere in the command line, actually.

How to import load a .sql or .csv file into SQLite?

Remember that the default delimiter for SQLite is the pipe "|"

sqlite> .separator ";"

sqlite> .import path/filename.txt tablename 

http://sqlite.awardspace.info/syntax/sqlitepg01.htm#sqlite010

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).

Examples:

  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

Git resolve conflict using --ours/--theirs for all files

Just grep through the working directory and send the output through the xargs command:

grep -lr '<<<<<<<' . | xargs git checkout --ours

or

grep -lr '<<<<<<<' . | xargs git checkout --theirs

How this works: grep will search through every file in the current directory (the .) and subdirectories recursively (the -r flag) looking for conflict markers (the string '<<<<<<<')

the -l or --files-with-matches flag causes grep to output only the filename where the string was found. Scanning stops after first match, so each matched file is only output once.

The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours or --theirs

More at this link.

Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.

This method should work through at least Git versions 2.4.x

How to import a CSS file in a React Component

You don't even have to name it if you don't need to:

e.g.

import React from 'react';
import './App.css';

see a complete example here (Build a JSX Live Compiler as a React Component).

How do I check for a network connection?

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <summary>
    /// Indicates whether any network connection is available
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable()
    {
        return IsNetworkAvailable(0);
    }

    /// <summary>
    /// Indicates whether any network connection is available.
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable(long minimumSpeed)
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            // discard because of standard reasons
            if ((ni.OperationalStatus != OperationalStatus.Up) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
                continue;

            // this allow to filter modems, serial, etc.
            // I use 10000000 as a minimum speed for most cases
            if (ni.Speed < minimumSpeed)
                continue;

            // discard virtual cards (virtual box, virtual pc, etc.)
            if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
                (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
                continue;

            // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
            if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
                continue;

            return true;
        }
        return false;
    }

How to enter special characters like "&" in oracle database?

you can simply escape & by following a dot. try this:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');

String.strip() in Python

In this case, you might get some differences. Consider a line like:

"foo\tbar "

In this case, if you strip, then you'll get {"foo":"bar"} as the dictionary entry. If you don't strip, you'll get {"foo":"bar "} (note the extra space at the end)

Note that if you use line.split() instead of line.split('\t'), you'll split on every whitespace character and the "striping" will be done during splitting automatically. In other words:

line.strip().split()

is always identical to:

line.split()

but:

line.strip().split(delimiter)

Is not necessarily equivalent to:

line.split(delimiter)

How to shut down the computer from C#

I tried roomaroo's WMI method to shutdown Windows 2003 Server, but it would not work until I added `[STAThread]' (i.e. "Single Threaded Apartment" threading model) to the Main() declaration:

[STAThread]
public static void Main(string[] args) {
    Shutdown();
}

I then tried to shutdown from a thread, and to get that to work I had to set the "Apartment State" of the thread to STA as well:

using System.Management;
using System.Threading;

public static class Program {

    [STAThread]
    public static void Main(string[] args) {
        Thread t = new Thread(new ThreadStart(Program.Shutdown));
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        ...
    }

    public static void Shutdown() {
        // roomaroo's code
    }
}

I'm a C# noob, so I'm not entirely sure of the significance of STA threads in terms of shutting down the system (even after reading the link I posted above). Perhaps someone else can elaborate...?

How do I get multiple subplots in matplotlib?

Iterating through all subplots sequentially:

fig, axes = plt.subplots(nrows, ncols)

for ax in axes.flatten():
    ax.plot(x,y)

Accessing a specific index:

for row in range(nrows):
    for col in range(ncols):
        axes[row,col].plot(x[row], y[col])

Boto3 to download all files from a S3 Bucket

I'm currently achieving the task, by using the following

#!/usr/bin/python
import boto3
s3=boto3.client('s3')
list=s3.list_objects(Bucket='bucket')['Contents']
for s3_key in list:
    s3_object = s3_key['Key']
    if not s3_object.endswith("/"):
        s3.download_file('bucket', s3_object, s3_object)
    else:
        import os
        if not os.path.exists(s3_object):
            os.makedirs(s3_object)

Although, it does the job, I'm not sure its good to do this way. I'm leaving it here to help other users and further answers, with better manner of achieving this

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

Changing background colour of tr element on mouseover

You could try:

tr:hover {
    background-color: #000;
}

tr:hover td {
    background-color: transparent; /* or #000 */
}

JS Fiddle demo.

How to view the committed files you have not pushed yet?

The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.

So if you are like me who work in a branch, here are tips:

  1. Say you are already on a branch. If not, git checkout that branch
  2. git log # to show a list of commit such as x08d46ffb1369e603c46ae96, You need only the latest commit which comes first.
  3. git show --name-only x08d46ffb1369e603c46ae96 # to show the files commited
  4. git show x08d46ffb1369e603c46ae96 # show the detail diff of each changed file

Or more simply, just use HEAD:

  1. git show --name-only HEAD # to show a list of files committed
  2. git show HEAD # to show the detail diff.

How to add button tint programmatically

simple we can also use for an imageview

    imageView.setColorFilter(ContextCompat.getColor(context,
R.color.COLOR_YOUR_COLOR));

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

Quick Solution for impatient people ;) On Windows machines, try this: Go to C:\Windows\System32 directory and delete java.exe (or rename it to something like java.exe.old).

Since at least 1.6, there should not be a java.exe in the Windows directory. If there is, it's a leftover from something.

A bit more reading:

I'm really suprised that a question from 2012 doesn't have an approved answer yet and I've actually encountered the same issue in 2015 on my Win 7 32-Bit OS!

So what did happen?

Basically, everything was working fine, I downloaded H2 database and when I tried to start H2 Console (Command Line) I got:

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

I found this question and I was able to confirm the same symptoms:

JAVA_HOME is set correctly:

echo %JAVA_HOME%
C:\Program Files\Java\jdk1.6.0_26

java -version fails, while java --fullversion works fine:

java -fullversion
java full version "1.6.0_45-b06"

SOLUTION: Go to C:\Windows\System32 directory and delete (I actually renamed) java.exe file!!!!

Now, I get:

java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)

and H2 Console (Command Line) works fine as well!

Credits go to the last post in this forum: https://bukkit.org/threads/java-lang-noclassdeffounderror-java-lang-object.70450/

String concatenation: concat() vs "+" operator

No, not quite.

Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

public class Concat {
    String cat(String a, String b) {
        a += b;
        return a;
    }
}

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

java.lang.String cat(java.lang.String, java.lang.String);
  Code:
   0:   new     #2; //class java/lang/StringBuilder
   3:   dup
   4:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   7:   aload_1
   8:   invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   11:  aload_2
   12:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   15:  invokevirtual   #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/    String;
   18:  astore_1
   19:  aload_1
   20:  areturn

So, a += b is the equivalent of

a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

How to sort an array of objects with jquery or javascript

var array = [[1, "grape", 42], [2, "fruit", 9]];

array.sort(function(a, b)
{
    // a and b will here be two objects from the array
    // thus a[1] and b[1] will equal the names

    // if they are equal, return 0 (no sorting)
    if (a[1] == b[1]) { return 0; }
    if (a[1] > b[1])
    {
        // if a should come after b, return 1
        return 1;
    }
    else
    {
        // if b should come after a, return -1
        return -1;
    }
});

The sort function takes an additional argument, a function that takes two arguments. This function should return -1, 0 or 1 depending on which of the two arguments should come first in the sorting. More info.

I also fixed a syntax error in your multidimensional array.

Compiling with g++ using multiple cores

I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).

JPA entity without id

I guess your entity_property has a composite key (entity_id, name) where entity_id is a foreign key to entity. If so, you can map it as follows:

@Embeddable
public class EntityPropertyPK {
    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "entity_id")
    private Entity entity;

    ...
}

@Entity 
@Table(name="entity_property") 
public class EntityProperty { 
    @EmbeddedId
    private EntityPropertyPK id;

    @Column(name = "value")
    private String value; 

    ...
}

Anaconda vs. miniconda

The 2 in Anaconda2 means that the main version of Python will be 2.x rather than the 3.x installed in Anaconda3. The current release has Python 2.7.13.

The 4.4.0.1 is the version number of Anaconda. The current advertised version is 4.4.0 and I assume the .1 is a minor release or for other similar use. The Windows releases, which I use, just say 4.4.0 in the file name.

Others have now explained the difference between Anaconda and Miniconda, so I'll skip that.

How to clear input buffer in C?

Short, portable and declared in stdio.h

stdin = freopen(NULL,"r",stdin);

Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:

while ((c = getchar()) != '\n' && c != EOF) { }

A little expensive so don't use it in a program that needs to repeatedly clear the buffer.

Stole from a coworker :)

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

Slide right to left Android Animations

See this link.. you can see so many kinds of animations here, just copy the xml to your res/anim folder and use it like the following..

listView.setAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_right));

Animation Lists

Using Environment Variables with Vue.js

In the root of your project create your environment files:

  • .env
  • .env.someEnvironment1
  • .env.SomeEnvironment2

To then load those configs, you would specify the environment via mode i.e.

npm run serve --mode development //default mode
npm run serve --mode someEnvironment1

In your env files you simply declare the config as key-value pairs, but if you're using vue 3, you must prefix with VUE_APP_:

In your .env:

VUE_APP_TITLE=This will get overwritten if more specific available

.env.someEnvironment1:

VUE_APP_TITLE=My App (someEnvironment1)

You can then use this in any of your components via:

myComponent.vue:

<template>
  <div> 
    {{title}}
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  data() {
    return {
      title: process.env.VUE_APP_TITLE
    };
  }
};
</script>

Now if you ran the app without a mode it will show the 'This will get...' but if you specify a someEnvironment1 as your mode then you will get the title from there.

You can create configs that are 'hidden' from git by appending .local to your file: .env.someEnvironment1.local - very useful for when you have secrets.

Read the docs for more info.

Generate random numbers uniformly over an entire range

You should look at RAND_MAX for your particular compiler/environment. I think you would see these results if rand() is producing a random 16-bit number. (you seem to be assuming it will be a 32-bit number).

I can't promise this is the answer, but please post your value of RAND_MAX, and a little more detail on your environment.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

I was facing the same problem because some of the images are grey scale images in my data set, so i solve my problem by doing this

    from PIL import Image
    img = Image.open('my_image.jpg').convert('RGB')
    # a line from my program
    positive_images_array = np.array([np.array(Image.open(img).convert('RGB').resize((150, 150), Image.ANTIALIAS)) for img in images_in_yes_directory])

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

How to check if two arrays are equal with JavaScript?

Even if this would seem super simple, sometimes it's really useful. If all you need is to see if two arrays have the same items and they are in the same order, try this:

[1, 2, 3].toString() == [1, 2, 3].toString()
true
[1, 2, 3,].toString() == [1, 2, 3].toString()
true
[1,2,3].toString() == [1, 2, 3].toString()
true

However, this doesn't work for mode advanced cases such as:

[[1,2],[3]].toString() == [[1],[2,3]].toString()
true

It depends what you need.

jQuery - Get Width of Element when Not Visible (Display: None)

If you need the width of something that's hidden and you can't un-hide it for whatever reason, you can clone it, change the CSS so it displays off the page, make it invisible, and then measure it. The user will be none the wiser if it's hidden and deleted afterwards.

Some of the other answers here just make the visibility hidden which works, but it will take up a blank spot on your page for a fraction of a second.

Example:

$itemClone = $('.hidden-item').clone().css({
        'visibility': 'hidden',
        'position': 'absolute',
        'z-index': '-99999',
        'left': '99999999px',
        'top': '0px'
    }).appendTo('body');
var width = $itemClone.width();
$itemClone.remove();

How to append text to a text file in C++?

I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.

static void appendLineToFile(string filepath, string line)
{
    std::ofstream file;
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message
    //file.exceptions(file.exceptions() | std::ios::failbit);
    file.open(filepath, std::ios::out | std::ios::app);
    if (file.fail())
        throw std::ios_base::failure(std::strerror(errno));

    //make sure write fails with exception if something is wrong
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);

    file << line << std::endl;
}

Rollback transaction after @Test

I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:

My test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest 

Context xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driverClassName}" />
   <property name="url" value="${jdbc.url}" />
   <property name="username" value="${jdbc.username}" />
   <property name="password" value="${jdbc.password}" />
</bean>

I still had the problem that, the database was not being cleaned up automatically.

Issue was resolved when I added following property to BasicDataSource

<property name="defaultAutoCommit" value="false" />

Hope it helps.

Is Python interpreted, or compiled, or both?

The CPU can only understand machine code indeed. For interpreted programs, the ultimate goal of an interpreter is to "interpret" the program code into machine code. However, usually a modern interpreted language does not interpret human code directly because it is too inefficient.

The Python interpreter first reads the human code and optimizes it to some intermediate code before interpreting it into machine code. That's why you always need another program to run a Python script, unlike in C++ where you can run the compiled executable of your code directly. For example, c:\Python27\python.exe or /usr/bin/python.

How to get rid of the "No bootable medium found!" error in Virtual Box?

The CD / DVD wanted to be on the IDE controller on my system, not the SATA controller

Visual Studio displaying errors even if projects build

REM DELETE ALL VS HIDDEN SOLUTION OPTION FILES
DEL /A:H /S *.SUO

List<T> OrderBy Alphabetical Order

You can use this code snippet:

var New1 = EmpList.OrderBy(z => z.Age).ToList();

where New1 is a List<Employee>.

EmpList is variable of a List<Employee>.

z is a variable of Employee type.

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

Try below:

SELECT CONVERT(VARCHAR(20), GETDATE(), 101)

android.widget.Switch - on/off event listener?

there are two ways,

  1. using xml onclick view Add Switch in XML as below:

    <Switch
    android:id="@+id/switch1"
    android:onClick="toggle"/>
    

In YourActivity Class (For E.g MainActivity.java)

    Switch toggle; //outside oncreate
    toggle =(Switch) findViewById(R.id.switch1); // inside oncreate

    public void toggle(View view) //outside oncreate
    {
        if( toggle.isChecked() ){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                start.setBackgroundColor(getColor(R.color.gold));
                stop.setBackgroundColor(getColor(R.color.white));
            }
        }
        else
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                stop.setBackgroundColor(getColor(R.color.gold));
                start.setBackgroundColor(getColor(R.color.white));
            }
        }
    }
  1. using on click listener

Add Switch in XML as below:

In YourActivity Class (For E.g MainActivity.java)

    Switch toggle; // outside oncreate
    toggle =(Switch) findViewById(R.id.switch1);  // inside oncreate


    toggle.setOnClickListener(new View.OnClickListener() {   // inside oncreate
        @Override
        public void onClick(View view) {

            if( toggle.isChecked() ){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    start.setBackgroundColor(getColor(R.color.gold));
                }
            }
            else
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    stop.setBackgroundColor(getColor(R.color.gold));
                }
            }

        }

    });

How do you properly determine the current script directory?

Would

import os
cwd = os.getcwd()

do what you want? I'm not sure what exactly you mean by the "current script directory". What would the expected output be for the use cases you gave?

Page scroll when soft keyboard popped up

You can try using the following code to solve your problem:

 <activity
     android:name=".DonateNow"
     android:label="@string/title_activity_donate_now"
     android:screenOrientation="portrait"
     android:theme="@style/AppTheme"
     android:windowSoftInputMode="stateVisible|adjustPan">
 </activity>

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )

How can I find WPF controls by name or type?

To find an ancestor of a given type from code, you can use:

[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
    while (true)
    {
        d = VisualTreeHelper.GetParent(d);

        if (d == null)
            return null;

        var t = d as T;

        if (t != null)
            return t;
    }
}

This implementation uses iteration instead of recursion which can be slightly faster.

If you're using C# 7, this can be made slightly shorter:

[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
    while (true)
    {
        d = VisualTreeHelper.GetParent(d);

        if (d == null)
            return null;

        if (d is T t)
            return t;
    }
}

jQuery get mouse position within an element

Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/

_x000D_
_x000D_
function ThzhotspotPosition(evt, el, hotspotsize, percent) {_x000D_
  var left = el.offset().left;_x000D_
  var top = el.offset().top;_x000D_
  var hotspot = hotspotsize ? hotspotsize : 0;_x000D_
  if (percent) {_x000D_
    x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';_x000D_
    y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';_x000D_
  } else {_x000D_
    x = (evt.pageX - left - (hotspot / 2));_x000D_
    y = (evt.pageY - top - (hotspot / 2));_x000D_
  }_x000D_
_x000D_
  return {_x000D_
    x: x,_x000D_
    y: y_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('.box').click(function(e) {_x000D_
_x000D_
    var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px_x000D_
_x000D_
    var hotspot = $('<div class="hotspot">').css({_x000D_
      left: hp.x,_x000D_
      top: hp.y,_x000D_
    });_x000D_
    $(this).append(hotspot);_x000D_
    $("span").text("X: " + hp.x + ", Y: " + hp.y);_x000D_
  });_x000D_
_x000D_
_x000D_
});
_x000D_
.box {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  background: #efefef;_x000D_
  margin: 20px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  top: 20px;_x000D_
  left: 20px;_x000D_
}_x000D_
_x000D_
.hotspot {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  background: green;_x000D_
  border-radius: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="box">_x000D_
  <p>Hotspot position is at: <span></span></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I profile C++ code running on Linux?

These are the two methods I use for speeding up my code:

For CPU bound applications:

  1. Use a profiler in DEBUG mode to identify questionable parts of your code
  2. Then switch to RELEASE mode and comment out the questionable sections of your code (stub it with nothing) until you see changes in performance.

For I/O bound applications:

  1. Use a profiler in RELEASE mode to identify questionable parts of your code.

N.B.

If you don't have a profiler, use the poor man's profiler. Hit pause while debugging your application. Most developer suites will break into assembly with commented line numbers. You're statistically likely to land in a region that is eating most of your CPU cycles.

For CPU, the reason for profiling in DEBUG mode is because if your tried profiling in RELEASE mode, the compiler is going to reduce math, vectorize loops, and inline functions which tends to glob your code into an un-mappable mess when it's assembled. An un-mappable mess means your profiler will not be able to clearly identify what is taking so long because the assembly may not correspond to the source code under optimization. If you need the performance (e.g. timing sensitive) of RELEASE mode, disable debugger features as needed to keep a usable performance.

For I/O-bound, the profiler can still identify I/O operations in RELEASE mode because I/O operations are either externally linked to a shared library (most of the time) or in the worst case, will result in a sys-call interrupt vector (which is also easily identifiable by the profiler).

How to find the privileges and roles granted to a user in Oracle?

select * 
from ROLE_TAB_PRIVS 
where role in (
    select granted_role
    from dba_role_privs 
    where granted_role in ('ROLE1','ROLE2')
)

Setting environment variables in Linux using Bash

The reason people often suggest writing

VAR=value
export VAR

instead of the shorter

export VAR=value

is that the longer form works in more different shells than the short form. If you know you're dealing with bash, either works fine, of course.

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Creating a LinkedList class from scratch

How about a fully functional implementation of a non-recursive Linked List?

I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.

Here's the code:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<T> implements Iterable<T> {
    private Node first;
    private Node last;
    private int N;

    public LinkedList() {
        first = null;
        last = null;
        N = 0;
    }

    public void add(T item) {
        if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
        if (!isEmpty()) {
            Node prev = last;
            last = new Node(item, null);
            prev.next = last;
        }
        else {
            last = new Node(item, null);
            first = last;
        }
        N++;
    }

    public boolean remove(T item) {
        if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
        boolean result = false;
        Node prev = first;
        Node curr = first;
        while (curr.next != null || curr == last) {
            if (curr.data.equals(item)) {
                // remove the last remaining element
                if (N == 1) { first = null; last = null; }
                // remove first element
                else if (curr.equals(first)) { first = first.next; }
                // remove last element
                else if (curr.equals(last)) { last = prev; last.next = null; }
                // remove element
                else { prev.next = curr.next; }
                N--;
                result = true;
                break;
            }
            prev = curr;
            curr = prev.next;
        }
        return result;
    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    private class Node {
        private T data;
        private Node next;

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

    public Iterator<T> iterator() { return new LinkedListIterator(); }

    private class LinkedListIterator implements Iterator<T> {
        private Node current = first;

        public T next() {
            if (!hasNext()) { throw new NoSuchElementException(); }
            T item = current.data;
            current = current.next;
            return item;
        }

        public boolean hasNext() { return current != null; }

        public void remove() { throw new UnsupportedOperationException(); }
    }

    @Override public String toString() {
        StringBuilder s = new StringBuilder();
        for (T item : this)
            s.append(item + " ");
        return s.toString();
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        while(!StdIn.isEmpty()) {
            String input = StdIn.readString();
            if (input.equals("print")) { StdOut.println(list.toString()); continue; }
            if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
            if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
            break;
        }
    }
}

Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.

If you want you could also look into implementing:

  • addFirst() - add a new item to the beginning of the LinkedList
  • removeFirst() - remove the first item from the LinkedList
  • removeLast() - remove the last item from the LinkedList
  • addAll() - add a list/array of items to the LinkedList
  • removeAll() - remove a list/array of items from the LinkedList
  • contains() - check to see if the LinkedList contains an item
  • contains() - clear all items in the LinkedList

Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.

The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.

There are 3 commands to test this in the debugger/console:

  • Prefixing a value by a '+' will add it to the list.
  • Prefixing with a '-' will remove the first occurrence from the list.
  • Typing 'print' will print out the list with the values separated by spaces.

If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:

  • add() - tacks a new node onto the end or initializes the first/last values if the list is empty
  • remove() - walks the list from the start-to-end. If it finds a match it removes that item and connects the broken links between the previous and next links in the chain. Special exceptions are added when there is no previous or next link.
  • toString() - uses the foreach iterator to simply walk the list chain from beginning-to-end.

While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.

How can you tell if a value is not numeric in Oracle?

You can use the following regular expression which will match integers (e.g., 123), floating-point numbers (12.3), and numbers with exponents (1.2e3):

^-?\d*\.?\d+([eE]-?\d+)?$

If you want to accept + signs as well as - signs (as Oracle does with TO_NUMBER()), you can change each occurrence of - above to [+-]. So you might rewrite your block of code above as follows:

IF (option_id = 0021) THEN 
    IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
        ip_msg(6214,option_name);
        RETURN;
    END IF;
END IF;

I am not altogether certain that would handle all values so you may want to add an EXCEPTION block or write a custom to_number() function as @JustinCave suggests.

Windows batch script to move files

This is exactly how it worked for me. For some reason the above code failed.

This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y

:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup

Java Error opening registry key

I have Windows 7. I got the same problem after installing: PyCharm. I wasn't satisfied with PyCharm, so I decided to use Eclipse instead. This is when I discovered that things went wrong with my JDK. I used to have Java.9.x. So I decided to uninstall it and get the newer version (at my time it was Java.11.x. The same problem persisted. I followed most of the steps mentioned above in the post like: - Removing all java*.exe files, - removing Java related entries from the registry. - Cleaning-up all unnecessary Java folders. However nothing helped. I still had something in the system referring to a broken Java pathname.

What really brought remedy is the following: - Uninstalled what ever version of JDK I had at the moment. - Re-Installed the last JDK version I had before the problem took place - Properly uninstall that version. - Install whatever latest version of SDK. ..

That's it .. at this point everything returned to normal ... Except that Java.11.xx did not fix the system path automatically, I had to do it manually.

What is "export default" in JavaScript?

export default function(){} can be used when the function doesn't have a name. There can only be one default export in a file. The alternative is a named export.

This page describes export default in detail as well as other details about modules that I found very helpful.

Fastest way to download a GitHub project

You say:

To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.

And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called "cloning the repository".

It's a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it's not always directly browsable). For the repository you mention, you would do:

$ git clone git://github.com/SpringSource/spring-data-graph-examples.git

The git:-type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository's history grows. There are options for that, but let's keep this simple.

I'm just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.

How do I get a PHP class constructor to call its parent's parent's constructor?

Another option that doesn't use a flag and might work in your situation:

<?php
// main class that everything inherits
class Grandpa 
{
    public function __construct(){
        $this->GrandpaSetup();
    }

    public function GrandpaSetup(){
        $this->prop1 = 'foo';
        $this->prop2 = 'bar';
    }
}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
        $this->prop1 = 'foobar';
    }

}
class Kiddo extends Papa
{
    public function __construct()
    {
        $this->GrandpaSetup();
    }
}

$kid = new Kiddo();
echo "{$kid->prop1}\n{$kid->prop2}\n";

How to set an environment variable in a running docker container

Firstly you can set env inside the container the same way as you do on a linux box.

Secondly, you can do it by modifying the config file of your docker container (/var/lib/docker/containers/xxxx/config.v2.json). Note you need restart docker service to take affect. This way you can change some other things like port mapping etc.

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

Automated testing for REST Api

At my work we have recently put together a couple of test suites written in Java to test some RESTful APIs we built. Our Services could invoke other RESTful APIs they depend on. We split it into two suites.


  • Suite 1 - Testing each service in isolation
    • Mock any peer services the API depends on using restito. Other alternatives include rest-driver, wiremock and betamax.
    • Tests the service we are testing and the mocks all run in a single JVM
    • Launches the service in Jetty

I would definitely recommend doing this. It has worked really well for us. The main advantages are:

  • Peer services are mocked, so you needn't perform any complicated data setup. Before each test you simply use restito to define how you want peer services to behave, just like you would with classes in unit tests with Mockito.
  • You can ask the mocked peer services if they were called. You can't do these asserts as easily with real peer services.
  • The suite is super fast as mocked services serve pre-canned in-memory responses. So we can get good coverage without the suite taking an age to run.
  • The suite is reliable and repeatable as its isolated in it's own JVM, so no need to worry about other suites/people mucking about with an shared environment at the same time the suite is running and causing tests to fail.

  • Suite 2 - Full End to End
    • Suite runs against a full environment deployed across several machines
    • API deployed on Tomcat in environment
    • Peer services are real 'as live' full deployments

This suite requires us to do data set up in peer services which means tests generally take more time to write. As much as possible we use REST clients to do data set up in peer services.

Tests in this suite usually take longer to write, so we put most of our coverage in Suite 1. That being said there is still clear value in this suite as our mocks in Suite 1 may not be behaving quite like the real services.


The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

One time page refresh after first page load

<script type="text/javascript">
$(document).ready(function(){    
    //Check if the current URL contains '#'
    if(document.URL.indexOf("#")==-1){
        // Set the URL to whatever it was plus "#".
        url = document.URL+"#";
        location = "#";

        //Reload the page
        location.reload(true);
    }
});
</script>

Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution. This works for me fine.

JDK was not found on the computer for NetBeans 6.5

For netbeans 8.2

1. First run command as administrator.
2. set path to you downloads folder using cd 'location to the downloads folder'
3. extract using netbeans-8.2-windows.exe --extract command
4. run java -jar bundle.jar
5. Done :)

How do I create a copy of an object in PHP?

I was doing some testing and got this:

class A {
  public $property;
}

function set_property($obj) {
  $obj->property = "after";
  var_dump($obj);
}

$a = new A();
$a->property = "before";

// Creates a new Object from $a. Like "new A();"
$b = new $a;
// Makes a Copy of var $a, not referenced.
$c = clone $a;

set_property($a);
// object(A)#1 (1) { ["property"]=> string(5) "after" }

var_dump($a); // Because function set_property get by reference
// object(A)#1 (1) { ["property"]=> string(5) "after" }
var_dump($b);
// object(A)#2 (1) { ["property"]=> NULL }
var_dump($c);
// object(A)#3 (1) { ["property"]=> string(6) "before" }

// Now creates a new obj A and passes to the function by clone (will copied)
$d = new A();
$d->property = "before";

set_property(clone $d); // A new variable was created from $d, and not made a reference
// object(A)#5 (1) { ["property"]=> string(5) "after" }

var_dump($d);
// object(A)#4 (1) { ["property"]=> string(6) "before" }

?>

AppFabric installation failed because installer MSI returned with error code : 1603

Although many links talk about deleting the trailing space in the environment variable, that did not apply to my case as there was no trailing space in my case.

https://serverfault.com/a/593339/270420

This was the answer that finally helped me out. I had to delete the AS_Observers and AS_Administrators groups created during previous installation attempt and then reinstall.

Doing this resolved the problem and I could successfully install AppFabric. Couldn't post this as answer in the server fault site due to insufficient reputation.

How can I add or update a query string parameter?

I have expanded the solution and combined it with another that I found to replace/update/remove the querystring parameters based on the users input and taking the urls anchor into consideration.

Not supplying a value will remove the parameter, supplying one will add/update the parameter. If no URL is supplied, it will be grabbed from window.location

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        } 
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            return url;
        }
        else {
            return url;
        }
    }
}

Update

There was a bug when removing the first parameter in the querystring, I have reworked the regex and test to include a fix.

Second Update

As suggested by @JarónBarends - Tweak value check to check against undefined and null to allow setting 0 values

Third Update

There was a bug where removing a querystring variable directly before a hashtag would lose the hashtag symbol which has been fixed

Fourth Update

Thanks @rooby for pointing out a regex optimization in the first RegExp object. Set initial regex to ([?&]) due to issue with using (\?|&) found by @YonatanKarni

Fifth Update

Removing declaring hash var in if/else statement

Emulator error: This AVD's configuration is missing a kernel file

See my answer for the Android Studio environment, Mac and “PANIC: Missing emulator engine program for 'arm' CPU.”.

To solve this problem, you need to specify the -kernel path manually. i.e.

$ ~/Library/Android/sdk/emulator/emulator  @Galaxy_Nexus_Jelly_Bean_API_16 -kernel ~/Library/Android/sdk/system-images/android-16/default/armeabi-v7a/kernel-qemu

Remember to change the emulator name Galaxy_Nexus_Jelly_Bean_API_16 to your own emulator name.

Below command is to check the emulators available for command line.

$ ~/Library/Android/sdk/emulator/emulator -list-avds

And also, ensure that your emulator path is correct, i.e. the one located at ~/Library/Android/sdk/emulator/.

Will #if RELEASE work like #if DEBUG does in C#?

No, it won't, unless you do some work.

The important part here is what DEBUG really is, and it's a kind of constant defined that the compiler can check against.

If you check the project properties, under the Build tab, you'll find three things:

  • A text box labelled "Conditional compilation symbols"
  • A check box labelled "Define DEBUG constant"
  • A check box labelled "Define TRACE constant"

There is no such checkbox, nor constant/symbol pre-defined that has the name RELEASE.

However, you can easily add that name to the text box labelled Conditional compilation symbols, but make sure you set the project configuration to Release-mode before doing so, as these settings are per configuration.

So basically, unless you add that to the text box, #if RELEASE won't produce any code under any configuration.

How do you debug MySQL stored procedures?

I do something very similar to you.

I'll usually include a DEBUG param that defaults to false and I can set to true at run time. Then wrap the debug statements into an "If DEBUG" block.

I also use a logging table with many of my jobs so that I can review processes and timing. My Debug code gets output there as well. I include the calling param name, a brief description, row counts affected (if appropriate), a comments field and a time stamp.

Good debugging tools is one of the sad failings of all SQL platforms.

How to disable Google asking permission to regularly check installed apps on my phone?

On Android prior to 4.2, go to Google Settings, tap Verify apps and uncheck the option Verify apps.

On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.

How to remove padding around buttons in Android?

For me the problem turned out to be minHeight and minWidth on some of the Android themes.

On the Button element, add:

<Button android:minHeight="0dp" android:minWidth="0dp" ...

Or in your button's style:

<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>

Is there a way to access an iteration-counter in Java's for-each loop?

Here is an example of how I did this. This gets the index at the for each loop. Hope this helps.

public class CheckForEachLoop {

    public static void main(String[] args) {

        String[] months = new String[] { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
                "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
        for (String s : months) {
            if (s == months[2]) { // location where you can change
              doSomethingWith(s); // however many times s and months
                                  // doSomethingWith(s) will be completed and 
                                  // added together instead of counter
            }

        }
        System.out.println(s); 


    }
}

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Use getElementById on HTMLElement instead of HTMLDocument

I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Set elements = .querySelectorAll(".profile-col1")
        For i = 0 To elements.Length - 1
            Debug.Print String(20, Chr$(61))
            Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
        Next
    End With
End Sub

References:

VBE > Tools > References > Microsoft HTML Object Library

UITextField text change event

One thing is you may have multiple UITextFields. So, give them a tag and then you can switch on the tags. Here's how to setup an observer in any class pretty much.

private func setupTextFieldNotification() {
    NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: nil, queue: OperationQueue.main) { (notification) in
        if let textField = notification.object as? UITextField, textField.tag == 100, let text = textField.text {
            print(#line, text)
        }
    }
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.

StartDate  
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))

End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))  

I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.

How did I do?

Conditional formatting based on another cell's value

I'm disappointed at how long it took to work this out.

I want to see which values in my range are outside standard deviation.

  1. Add the standard deviation calc to a cell somewhere =STDEV(L3:L32)*2
  2. Select the range to be highlighted, right click, conditional formatting
  3. Pick Format Cells if Greater than
  4. In the Value or Formula box type =$L$32 (whatever cell your stdev is in)

I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I was able to resolve the same problem with maven-antrun-plugin and jaxb2-maven-plugin in Eclipse Kepler 4.3 by appying this solution: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#Eclipse_4.2_add_default_mapping
So the content of my %elipse_workspace_name%/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <versionRange>1.3</versionRange>
        <goals>
          <goal>run</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <versionRange>1.2</versionRange>
        <goals>
          <goal>xjc</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

*Had to restart Eclipse to see the errors gone.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :

"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!

In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.

Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."

Link a photo with the cell in excel

Select both the column you are sorting, and the column that the picture is in (I am assuming the picture is small compared to the cell, i.e. it is "in" the cell). Make sure that the object positioning property is set as "move but don't size with cells". Now if you do a sort, the pictures will move with the list being sorted.

Note - you must include the column with the picture in your range when you sort, and the picture must fit inside the cell.

The following VBA snippet will make sure all pictures in your spreadsheet have their "move and size" property set:

Sub moveAndSize()
Dim s As Shape
For Each s In ActiveSheet.Shapes
  If s.Type = msoPicture Or s.Type = msoLinkedPicture Or s.Type = msoPlaceholder Then
    s.Placement = xlMove
  End If
Next
End Sub

If you want to make sure the picture continues to fit after you move it, you can use xlMoveAndSize instead of xlMove.

window.close and self.close do not close the window in Chrome

Many people are still trying to find a way to close the Chrome browser using javascript. The following method only works when you use Chrome as APP launcher - kiosk for example!

I have tested the following:

I'm using the following extension: Close Kiosk

I'm following the usage instructions and it seems to work just fine (make sure you clear the cache while doing the tests). The javascript I use is (attached to click event):

window.location.href = '/closekiosk';

I hope that helps somebody, as it's the only working solution I have found.

Note: It seems the extension runs in background and adds a Chrome tray icon. It has the following option checked: "Let Chrome run in background" (or similar text). You may need to play with it, until it work for you. I unchecked it and now it works just fine!

Freeze screen in chrome debugger / DevTools panel for popover inspection?

Got it working. Here was my procedure:

  1. Browse to the desired page
  2. Open the dev console - F12 on Windows/Linux or option + ? + J on macOS
  3. Select the Sources tab in chrome inspector
  4. In the web browser window, hover over the desired element to initiate the popover
  5. Hit F8 on Windows/Linux (or fn + F8 on macOS) while the popover is showing. If you have clicked anywhere on the actual page F8 will do nothing. Your last click needs to be somewhere in the inspector, like the sources tab
  6. Go to the Elements tab in inspector
  7. Find your popover (it will be nested in the trigger element's HTML)
  8. Have fun modifying the CSS

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

How to fix "Headers already sent" error in PHP

I got this error many times before, and I am certain all PHP programmer got this error at least once before.

Possible Solution 1

This error may have been caused by the blank spaces before the start of the file or after the end of the file.These blank spaces should not be here.

ex) THERE SHOULD BE NO BLANK SPACES HERE

   echo "your code here";

?>
THERE SHOULD BE NO BLANK SPACES HERE

Check all files associated with file that causes this error.

Note: Sometimes EDITOR(IDE) like gedit (a default linux editor) add one blank line on save file. This should not happen. If you are using Linux. you can use VI editor to remove space/lines after ?> at the end of the page.

Possible Solution 2: If this is not your case, then use ob_start to output buffering:

<?php
  ob_start();

  // code 

 ob_end_flush();
?> 

This will turn output buffering on and your headers will be created after the page is buffered.

URL Encode a string in jQuery for an AJAX request

Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:

var encoded = encodeURIComponent(str);

How may I sort a list alphabetically using jQuery?

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort

%Like% Query in spring JpaRepository

You can also implement the like queries using Spring Data JPA supported keyword "Containing".

List<Registration> findByPlaceContaining(String place);

How to make Twitter bootstrap modal full screen

You need to set your DIV tags as below.

Find the more details > http://thedeveloperblog.com/bootstrap-modal-with-full-size-and-scrolling

</style>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
   More Details
</button>
</br>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-content">
        <div class="container">;
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h3 class="modal-title" id="myModalLabel">Modal Title</h3>
          </div>
              <div class="modal-body" >
                Your modal text 
              </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
    </div>                                      
</div>

How do you set your pythonpath in an already-created virtualenv?

The most elegant solution to this problem is here.

Original answer remains, but this is a messy solution:


If you want to change the PYTHONPATH used in a virtualenv, you can add the following line to your virtualenv's bin/activate file:

export PYTHONPATH="/the/path/you/want"

This way, the new PYTHONPATH will be set each time you use this virtualenv.

EDIT: (to answer @RamRachum's comment)

To have it restored to its original value on deactivate, you could add

export OLD_PYTHONPATH="$PYTHONPATH"

before the previously mentioned line, and add the following line to your bin/postdeactivate script.

export PYTHONPATH="$OLD_PYTHONPATH"

Copy all values in a column to a new column in a pandas dataframe

You can simply assign the B to the new column , Like -

df['D'] = df['B']

Example/Demo -

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([['a.1','b.1','c.1'],['a.2','b.2','c.2'],['a.3','b.3','c.3']],columns=['A','B','C'])

In [3]: df
Out[3]:
     A    B    C
0  a.1  b.1  c.1
1  a.2  b.2  c.2
2  a.3  b.3  c.3

In [4]: df['D'] = df['B']                  #<---What you want.

In [5]: df
Out[5]:
     A    B    C    D
0  a.1  b.1  c.1  b.1
1  a.2  b.2  c.2  b.2
2  a.3  b.3  c.3  b.3

In [6]: df.loc[0,'D'] = 'd.1'

In [7]: df
Out[7]:
     A    B    C    D
0  a.1  b.1  c.1  d.1
1  a.2  b.2  c.2  b.2
2  a.3  b.3  c.3  b.3

How to use jQuery with Angular?

Just write

declare var $:any;

after all import sections, you can use jQuery and include the jQuery library in your index.html page

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

it worked for me

Show popup after page load

When the DOM is finished loading you can add your code in the $(document).ready() function.

Remove the onclick from here:

<input type="submit" name="submit" value="Submit" onClick="PopUp()" />

Try this:

$(document).ready(function(){
   setTimeout(function(){
      PopUp();
   },5000); // 5000 to load it after 5 seconds from page load
});

MySQL count occurrences greater than 2

SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1

How to get multiple selected values from select box in JSP?

Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.

Update: save the file as test.jsp and run it on any web/app server

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

SQL Server Group by Count of DateTime Per Hour?

You can also achieve this by using following SQL with date and hour in same columns and proper date time format and ordered by date time

SELECT  dateadd(hour, datediff(hour, 0, StartDate), 0) as 'ForDate', 
    COUNT(*) as 'Count' 
FROM #Events
GROUP BY dateadd(hour, datediff(hour, 0, LogTime), 0)
ORDER BY ForDate

How can I completely remove TFS Bindings

  1. Go to File -> Source Control -> Advanced -> Change Source Control (if change source control doesn't appear, click on solution in the solution explorer then try again)
  2. Unbind solution and all projects

Now right click on solution and you will see "Add Project To Source Control". if you want to add project to source control again you might be get some errors that ask you to change the solution folder on TFS. it happens because your solution has some mapping in a workspace yet. remove mapping or delete workspace. now your solution is completely unbind and unmapped from TFS or workspaces.

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

Using class members to give default values works very well just so long as you are careful only to do it with immutable values. If you try to do it with a list or a dict that would be pretty deadly. It also works where the instance attribute is a reference to a class just so long as the default value is None.

I've seen this technique used very successfully in repoze which is a framework that runs on top of Zope. The advantage here is not just that when your class is persisted to the database only the non-default attributes need to be saved, but also when you need to add a new field into the schema all the existing objects see the new field with its default value without any need to actually change the stored data.

I find it also works well in more general coding, but it's a style thing. Use whatever you are happiest with.

Unable to Connect to GitHub.com For Cloning

Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.

Does C# have a String Tokenizer like Java's?

I think the nearest in the .NET Framework is

string.Split()

Redeploy alternatives to JRebel

JRebel is free. Don't buy it. Select the "free" option (radio button) on the "buy" page. Then select "Social". After you sign up, you will get a fully functional JRebel license key. You can then download JRebel or use the key in your IDEs embedded version. The catch, (yes, there is a catch), you have to allow them to post on your behalf (advertise) once a month on your FB timeline or Twitter account. I gave them my twitter account, no biggie, I never use it and no one I know really uses it. So save $260.

Tips for debugging .htaccess rewrite rules

as pointed out by @JCastell, the online tester does a good job of testing individual redirects against an .htaccess file. However, more interesting is the api exposed which can be used to batch test a list of urls using a json object. However, to make it more useful, I have written a small bash script file which makes use of curl and jq to submit a list of urls and parse the json response into a CSV formated output with the line number and rule matched in the htaccess file along with the redirected url, making it quite handy to compare a list of urls in a spreadsheet and quickly determine which rules are not working.

How to disable scrolling in UITableView table when the content fits on the screen

You can verify the number of visible cells using this function:

- (NSArray *)visibleCells

This method will return an array with the cells that are visible, so you can count the number of objects in this array and compare with the number of objects in your table.. if it's equal.. you can disable the scrolling using:

tableView.scrollEnabled = NO;

As @Ginny mentioned.. we would can have problems with partially visible cells, so this solution works better in this case:

tableView.scrollEnabled = (tableView.contentSize.height <= CGRectGetHeight(tableView.frame));

In case you are using autoLayout this solution do the job:

tableView.alwaysBounceVertical = NO.

AngularJS disable partial caching on dev machine

I found that the HTTP interceptor method works pretty nicely, and allows additional flexibility & control. Additionally, you can cache-bust for each production release by using a release hash as the buster variable.

Here is what the dev cachebusting method looks like using Date.

app.factory('cachebustInjector', function(conf) {   
    var cachebustInjector = {
        request: function(config) {    
            // new timestamp will be appended to each new partial .html request to prevent caching in a dev environment               
            var buster = new Date().getTime();

            if (config.url.indexOf('static/angular_templates') > -1) {
                config.url += ['?v=', buster].join('');
            }
            return config;
        }
    };
    return cachebustInjector;
});

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('cachebustInjector');
}]);

Click outside menu to close in jquery

I have recently faced the same issue. I wrote the following code:

    $('html').click(function(e) {
      var a = e.target;
      if ($(a).parents('.menu_container').length === 0) {
        $('.ofSubLevelLinks').removeClass('active'); //hide menu item
        $('.menu_container li > img').hide(); //hide dropdown image, if any
     }
    });

It has worked for me perfectly.

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

HTML table with 100% width, with vertical scroll inside tbody

Adding a fixed width to td,th after making tbody & thead display block works perfectly and also we can use slimscroll plugin to make the scroll bar beautiful.

enter image description here

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <title> Scrollable table </title>_x000D_
    <style>_x000D_
        body {_x000D_
            font-family: sans-serif;_x000D_
            font-size: 0.9em;_x000D_
        }_x000D_
        table {_x000D_
            border-collapse: collapse;_x000D_
            border-bottom: 1px solid #ddd;_x000D_
        }_x000D_
        thead {_x000D_
            background-color: #333;_x000D_
            color: #fff;_x000D_
        }_x000D_
        thead,tbody {_x000D_
            display: block;_x000D_
        }_x000D_
        th,td {_x000D_
            padding: 8px 10px;_x000D_
            border: 1px solid #ddd;_x000D_
            width: 117px;_x000D_
            box-sizing: border-box;_x000D_
        }_x000D_
        tbody {_x000D_
            height: 160px;_x000D_
            overflow-y: scroll_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <table class="example-table">_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th> Header 1 </th>_x000D_
                <th> Header 2 </th>_x000D_
                <th> Header 3 </th>_x000D_
                <th> Header 4 </th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
            <tr>_x000D_
                <td> Row 1- Col 1 </td>_x000D_
                <td> Row 1- Col 2 </td>_x000D_
                <td> Row 1- Col 3 </td>_x000D_
                <td> Row 1- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 2- Col 1 </td>_x000D_
                <td> Row 2- Col 2 </td>_x000D_
                <td> Row 2- Col 3 </td>_x000D_
                <td> Row 2- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 3- Col 1 </td>_x000D_
                <td> Row 3- Col 2 </td>_x000D_
                <td> Row 3- Col 3 </td>_x000D_
                <td> Row 3- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 4- Col 1 </td>_x000D_
                <td> Row 4- Col 2 </td>_x000D_
                <td> Row 4- Col 3 </td>_x000D_
                <td> Row 4- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 5- Col 1 </td>_x000D_
                <td> Row 5- Col 2 </td>_x000D_
                <td> Row 5- Col 3 </td>_x000D_
                <td> Row 5- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 6- Col 1 </td>_x000D_
                <td> Row 6- Col 2 </td>_x000D_
                <td> Row 6- Col 3 </td>_x000D_
                <td> Row 6- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 7- Col 1 </td>_x000D_
                <td> Row 7- Col 2 </td>_x000D_
                <td> Row 7- Col 3 </td>_x000D_
                <td> Row 7- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 8- Col 1 </td>_x000D_
                <td> Row 8- Col 2 </td>_x000D_
                <td> Row 8- Col 3 </td>_x000D_
                <td> Row 8- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 9- Col 1 </td>_x000D_
                <td> Row 9- Col 2 </td>_x000D_
                <td> Row 9- Col 3 </td>_x000D_
                <td> Row 9- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 10- Col 1 </td>_x000D_
                <td> Row 10- Col 2 </td>_x000D_
                <td> Row 10- Col 3 </td>_x000D_
                <td> Row 10- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 11- Col 1 </td>_x000D_
                <td> Row 11- Col 2 </td>_x000D_
                <td> Row 11- Col 3 </td>_x000D_
                <td> Row 11- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 12- Col 1 </td>_x000D_
                <td> Row 12- Col 2 </td>_x000D_
                <td> Row 12- Col 3 </td>_x000D_
                <td> Row 12- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 13- Col 1 </td>_x000D_
                <td> Row 13- Col 2 </td>_x000D_
                <td> Row 13- Col 3 </td>_x000D_
                <td> Row 13- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 14- Col 1 </td>_x000D_
                <td> Row 14- Col 2 </td>_x000D_
                <td> Row 14- Col 3 </td>_x000D_
                <td> Row 14- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 15- Col 1 </td>_x000D_
                <td> Row 15- Col 2 </td>_x000D_
                <td> Row 15- Col 3 </td>_x000D_
                <td> Row 15- Col 4 </td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td> Row 16- Col 1 </td>_x000D_
                <td> Row 16- Col 2 </td>_x000D_
                <td> Row 16- Col 3 </td>_x000D_
                <td> Row 16- Col 4 </td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
_x000D_
_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.min.js"></script>_x000D_
    <script>_x000D_
        $('.example-table tbody').slimscroll({_x000D_
            height: '160px',_x000D_
            alwaysVisible: true,_x000D_
            color: '#333'_x000D_
        })_x000D_
    </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to use Object.values with typescript?

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

For me it was happening in VS2017 and VS2019. It stopped happening after I selected the option "Suppressed JIT optimization on module load".

enter image description here

What is the best way to use a HashMap in C++?

Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:

#include <iostream>
#include <unordered_map>

class Hashtable {
    std::unordered_map<const void *, const void *> htmap;

public:
    void put(const void *key, const void *value) {
            htmap[key] = value;
    }

    const void *get(const void *key) {
            return htmap[key];
    }

};

int main() {
    Hashtable ht;
    ht.put("Bob", "Dylan");
    int one = 1;
    ht.put("one", &one);
    std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}

Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)

How do I update Anaconda?

Here's the best practice (in my humble experience). Selecting these four packages will also update all other dependencies to the appropriate versions that will help you keep your environment consistent. The latter is a common problem others have expressed in earlier responses. This solution doesn't need the terminal.

Updating and upgrading Anaconda 3 or Anaconda 2 best practice

Apache won't follow symlinks (403 Forbidden)

Related to this question, I just figured out why my vhost was giving me that 403.

I had tested ALL possibilities on this question and others without luck. It almost drives me mad.

I am setting up a server with releases deployment similar to Capistrano way through symlinks and when I tried to access the DocRoot folder (which is now a symlink to current release folder) it gave me the 403.

My vhost is:

DocumentRoot /var/www/site.com/html
<Directory /var/www/site.com/html>
        AllowOverride All
        Options +FollowSymLinks
        Require all granted
</Directory>

and my main httpd.conf file was (default Apache 2.4 install):

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes -FollowSymLinks -Includes
(...)

It turns out that the main Options definition was taking precedence over my vhosts fiel (for me that is counter intuitive). So I've changed it to:

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes +FollowSymLinks -Includes
(...)

and Eureka! (note the plus sign before FollowSymLinks in MAIN httpd.conf file. Hope this help some other lost soul.

ADB error: cannot connect to daemon

This answer may help some. The adb.exe has problems with virtual devices when you are using your phone for tethering. If you turn off tethering it will correct the problem.

Passing by reference in C

In C everything is pass-by-value. The use of pointers gives us the illusion that we are passing by reference because the value of the variable changes. However, if you were to print out the address of the pointer variable, you will see that it doesn't get affected. A copy of the value of the address is passed-in to the function. Below is a snippet illustrating that.

void add_number(int *a) {
    *a = *a + 2;
}

int main(int argc, char *argv[]) {
   int a = 2;

   printf("before pass by reference, a == %i\n", a);
   add_number(&a);
   printf("after  pass by reference, a == %i\n", a);

   printf("before pass by reference, a == %p\n", &a);
   add_number(&a);
   printf("after  pass by reference, a == %p\n", &a);

}

before pass by reference, a == 2
after  pass by reference, a == 4
before pass by reference, a == 0x7fff5cf417ec
after  pass by reference, a == 0x7fff5cf417ec

How do I shut down a python simpleHTTPserver?

if you have started the server with

python -m SimpleHTTPServer 8888 

then you can press ctrl + c to down the server.

But if you have started the server with

python -m SimpleHTTPServer 8888 &

or

python -m SimpleHTTPServer 8888 & disown

you have to see the list first to kill the process,

run command

ps

or

ps aux | less

it will show you some running process like this ..

PID TTY          TIME CMD
7247 pts/3     00:00:00 python
7360 pts/3     00:00:00 ps
23606 pts/3    00:00:00 bash

you can get the PID from here. and kill that process by running this command..

kill -9 7247

here 7247 is the python id.

Also for some reason if the port still open you can shut down the port with this command

fuser -k 8888/tcp

here 8888 is the tcp port opened by python.

Hope its clear now.

Is it possible to save HTML page as PDF using JavaScript or jquery?

Yes, Use jspdf To create a pdf file.

You can then turn it into a data URI and inject a download link into the DOM

You will however need to write the HTML to pdf conversion yourself.

Just use printer friendly versions of your page and let the user choose how he wants to print the page.

Edit: Apparently it has minimal support

So the answer is write your own PDF writer or get a existing PDF writer to do it for you (on the server).

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

Here is solution for Appache httpclient 4.5.11. I had problem with cert which has subject wildcarded *.hostname.com. It returned me same exception, but I musn't use disabling by property System.setProperty("jsse.enableSNIExtension", "false"); because it made error in Google location client.

I found simple solution (only modifying socket):

import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;

import javax.inject.Named;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.util.List;

@Factory
public class BeanFactory {

    @Bean
    @Named("without_verify")
    public HttpClient provideHttpClient() {
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), NoopHostnameVerifier.INSTANCE) {
            @Override
            protected void prepareSocket(SSLSocket socket) throws IOException {
                SSLParameters parameters = socket.getSSLParameters();
                parameters.setServerNames(List.of());
                socket.setSSLParameters(parameters);
                super.prepareSocket(socket);
            }
        };

        return HttpClients.custom()
                .setSSLSocketFactory(connectionSocketFactory)
                .build();
    }


}

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

You don't need to use JsonConverterAttribute, keep your model clean, also use CustomCreationConverter, the code is simpler:

public class SampleConverter : CustomCreationConverter<ISample>
{
    public override ISample Create(Type objectType)
    {
        return new Sample();
    }
}

Then:

var sz = JsonConvert.SerializeObject( sampleGroupInstance );
JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());

Documentation: Deserialize with CustomCreationConverter

Objective-C: Reading a file line by line

You can use NSInputStream which has a basic implementation for file streams. You can read bytes into a buffer (read:maxLength: method). You have to scan the buffer for newlines yourself.

Can we cast a generic object to a custom object type in javascript?

The answer of @PeterOlson may be worked back in the day but it looks like Object.create is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.

Nowadays we can use Object.assign (credits to @SayanPal solution) & ES6 syntax:

class Person {
  constructor(obj) {
    obj && Object.assign(this, obj);
  }

  getFullName() {
    return `${this.lastName} ${this.firstName}`;
  }
}

Usage:

const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon

ES5 answer below

function Person(obj) {
    for(var prop in obj){
        // for safety you can use the hasOwnProperty function
        this[prop] = obj[prop];
    }
}

Usage:

var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon

Using a shorter version, 1.5 liner:

function Person(){
    if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}

jsfiddle

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

How do I remove a file from the FileList

This question has already been marked answered, but I'd like to share some information that might help others with using FileList.

It would be convenient to treat a FileList as an array, but methods like sort, shift, pop, and slice don't work. As others have suggested, you can copy the FileList to an array. However, rather than using a loop, there's a simple one line solution to handle this conversion.

 // fileDialog.files is a FileList 

 var fileBuffer=[];

 // append the file list to an array
 Array.prototype.push.apply( fileBuffer, fileDialog.files ); // <-- here

 // And now you may manipulated the result as required

 // shift an item off the array
 var file = fileBuffer.shift(0,1);  // <-- works as expected
 console.info( file.name + ", " + file.size + ", " + file.type );

 // sort files by size
 fileBuffer.sort(function(a,b) {
    return a.size > b.size ? 1 : a.size < b.size ? -1 : 0;
 });

Tested OK in FF, Chrome, and IE10+

Auto insert date and time in form input field?

$("#startDate").val($.datepicker.formatDate("dd/mm/yy", new Date()));
$("#endDate").val($.datepicker.formatDate("dd/mm/yy", new Date()));

Add the above code at the end of the script. This is required because the datepicker plugin has no provision to set the date in the control while initializing.

How to extract URL parameters from a URL with Ruby or Rails?

Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:

require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
uri.query_values['param1']
=> 'value1'

(It also apparently handles param encoding/decoding, unlike URI)

Case insensitive access for generic dictionary

There's no way to specify a StringComparer at the point where you try to get a value. If you think about it, "foo".GetHashCode() and "FOO".GetHashCode() are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.

You can, however, create a case-insensitive dictionary in the first place using:-

var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);

Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-

var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);

This new dictionary then uses the GetHashCode() implementation on StringComparer.OrdinalIgnoreCase so comparer.GetHashCode("foo") and comparer.GetHashcode("FOO") give you the same value.

Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>> and just iterate over it:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;

Or if you prefer, without the LINQ:-

var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
  if (String.Equals(element.Key, myKey, comparer))
  {
    value = element.Value;
    break;
  }
}

This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).

How to hide console window in python?

On Unix Systems (including GNU/Linux, macOS, and BSD)

Use nohup mypythonprog &, and you can close the terminal window without disrupting the process. You can also run exit if you are running in the cloud and don't want to leave a hanging shell process.

On Windows Systems

Save the program with a .pyw extension and now it will open with pythonw.exe. No shell window.

For example, if you have foo.py, you need to rename it to foo.pyw.

React onClick function fires on render

The value for your onClick attribute should be a function, not a function call.

<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>

Breaking out of a nested loop

It seems to me like people dislike a goto statement a lot, so I felt the need to straighten this out a bit.

I believe the 'emotions' people have about goto eventually boil down to understanding of code and (misconceptions) about possible performance implications. Before answering the question, I will therefore first go into some of the details on how it's compiled.

As we all know, C# is compiled to IL, which is then compiled to assembler using an SSA compiler. I'll give a bit of insights into how this all works, and then try to answer the question itself.

From C# to IL

First we need a piece of C# code. Let's start simple:

foreach (var item in array)
{
    // ... 
    break;
    // ...
}

I'll do this step by step to give you a good idea of what happens under the hood.

First translation: from foreach to the equivalent for loop (Note: I'm using an array here, because I don't want to get into details of IDisposable -- in which case I'd also have to use an IEnumerable):

for (int i=0; i<array.Length; ++i)
{
    var item = array[i];
    // ...
    break;
    // ...
}

Second translation: the for and break is translated into an easier equivalent:

int i=0;
while (i < array.Length)
{
    var item = array[i];
    // ...
    break;
    // ...
    ++i;
}

And third translation (this is the equivalent of the IL code): we change break and while into a branch:

    int i=0; // for initialization

startLoop:
    if (i >= array.Length) // for condition
    {
        goto exitLoop;
    }
    var item = array[i];
    // ...
    goto exitLoop; // break
    // ...
    ++i;           // for post-expression
    goto startLoop; 

While the compiler does these things in a single step, it gives you insight into the process. The IL code that evolves from the C# program is the literal translation of the last C# code. You can see for yourself here: https://dotnetfiddle.net/QaiLRz (click 'view IL')

Now, one thing you have observed here is that during the process, the code becomes more complex. The easiest way to observe this is by the fact that we needed more and more code to ackomplish the same thing. You might also argue that foreach, for, while and break are actually short-hands for goto, which is partly true.

From IL to Assembler

The .NET JIT compiler is an SSA compiler. I won't go into all the details of SSA form here and how to create an optimizing compiler, it's just too much, but can give a basic understanding about what will happen. For a deeper understanding, it's best to start reading up on optimizing compilers (I do like this book for a brief introduction: http://ssabook.gforge.inria.fr/latest/book.pdf ) and LLVM (llvm.org).

Every optimizing compiler relies on the fact that code is easy and follows predictable patterns. In the case of FOR loops, we use graph theory to analyze branches, and then optimize things like cycli in our branches (e.g. branches backwards).

However, we now have forward branches to implement our loops. As you might have guessed, this is actually one of the first steps the JIT is going to fix, like this:

    int i=0; // for initialization

    if (i >= array.Length) // for condition
    {
        goto endOfLoop;
    }

startLoop:
    var item = array[i];
    // ...
    goto endOfLoop; // break
    // ...
    ++i;           // for post-expression

    if (i >= array.Length) // for condition
    {
        goto startLoop;
    }

endOfLoop:
    // ...

As you can see, we now have a backward branch, which is our little loop. The only thing that's still nasty here is the branch that we ended up with due to our break statement. In some cases, we can move this in the same way, but in others it's there to stay.

So why does the compiler do this? Well, if we can unroll the loop, we might be able to vectorize it. We might even be able to proof that there's just constants being added, which means our whole loop could vanish into thin air. To summarize: by making the patterns predictable (by making the branches predictable), we can proof that certain conditions hold in our loop, which means we can do magic during the JIT optimization.

However, branches tend to break those nice predictable patterns, which is something optimizers therefore kind-a dislike. Break, continue, goto - they all intend to break these predictable patterns- and are therefore not really 'nice'.

You should also realize at this point that a simple foreach is more predictable then a bunch of goto statements that go all over the place. In terms of (1) readability and (2) from an optimizer perspective, it's both the better solution.

Another thing worth mentioning is that it's very relevant for optimizing compilers to assign registers to variables (a process called register allocation). As you might know, there's only a finite number of registers in your CPU and they are by far the fastest pieces of memory in your hardware. Variables used in code that's in the inner-most loop, are more likely to get a register assigned, while variables outside of your loop are less important (because this code is probably hit less).

Help, too much complexity... what should I do?

The bottom line is that you should always use the language constructs you have at your disposal, which will usually (implictly) build predictable patterns for your compiler. Try to avoid strange branches if possible (specifically: break, continue, goto or a return in the middle of nothing).

The good news here is that these predictable patterns are both easy to read (for humans) and easy to spot (for compilers).

One of those patterns is called SESE, which stands for Single Entry Single Exit.

And now we get to the real question.

Imagine that you have something like this:

// a is a variable.

for (int i=0; i<100; ++i) 
{
  for (int j=0; j<100; ++j)
  {
     // ...

     if (i*j > a) 
     {
        // break everything
     }
  }
}

The easiest way to make this a predictable pattern is to simply eliminate the if completely:

int i, j;
for (i=0; i<100 && i*j <= a; ++i) 
{
  for (j=0; j<100 && i*j <= a; ++j)
  {
     // ...
  }
}

In other cases you can also split the method into 2 methods:

// Outer loop in method 1:

for (i=0; i<100 && processInner(i); ++i) 
{
}

private bool processInner(int i)
{
  int j;
  for (j=0; j<100 && i*j <= a; ++j)
  {
     // ...
  }
  return i*j<=a;
}

Temporary variables? Good, bad or ugly?

You might even decide to return a boolean from within the loop (but I personally prefer the SESE form because that's how the compiler will see it and I think it's cleaner to read).

Some people think it's cleaner to use a temporary variable, and propose a solution like this:

bool more = true;
for (int i=0; i<100; ++i) 
{
  for (int j=0; j<100; ++j) 
  {
     // ...
     if (i*j > a) { more = false; break; } // yuck.
     // ...
  }
  if (!more) { break; } // yuck.
  // ...
}
// ...

I personally am opposed to this approach. Look again on how the code is compiled. Now think about what this will do with these nice, predictable patterns. Get the picture?

Right, let me spell it out. What will happen is that:

  • The compiler will write out everything as branches.
  • As an optimization step, the compiler will do data flow analysis in an attempt to remove the strange more variable that only happens to be used in control flow.
  • If succesful, the variable more will be eliminated from the program, and only branches remain. These branches will be optimized, so you will get only a single branch out of the inner loop.
  • If unsuccesful, the variable more is definitely used in the inner-most loop, so if the compiler won't optimize it away, it has a high chance to be allocated to a register (which eats up valuable register memory).

So, to summarize: the optimizer in your compiler will go into a hell of a lot of trouble to figure out that more is only used for the control flow, and in the best case scenario will translate it to a single branch outside of the outer for loop.

In other words, the best case scenario is that it will end up with the equivalent of this:

for (int i=0; i<100; ++i) 
{
  for (int j=0; j<100; ++j)
  {
     // ...
     if (i*j > a) { goto exitLoop; } // perhaps add a comment
     // ...
  }
  // ...
}
exitLoop:

// ...

My personal opinion on this is quite simple: if this is what we intended all along, let's make the world easier for both the compiler and readability, and write that right away.

tl;dr:

Bottom line:

  • Use a simple condition in your for loop if possible. Stick to the high-level language constructs you have at your disposal as much as possible.
  • If everything fails and you're left with either goto or bool more, prefer the former.

jquery ui Dialog: cannot call methods on dialog prior to initialization

The new jQuery UI version will not allow you to call UI methods on dialog which is not initialized. As a workaround, you can use the below check to see if the dialog is alive.

if (modalDialogObj.hasClass('ui-dialog-content')) {
    // call UI methods like modalDialogObj.dialog('isOpen')
} else {
    // it is not initialized yet
}

How to filter multiple values (OR operation) in angularJS

If you want to filter on Array of Objects then you can give

filter:({genres: 'Action', key :value }.

Individual property will be filtered by particular filter given for that property.

But if you wanted to something like filter by individual Property and filter globally for all properties then you can do something like this.

_x000D_
_x000D_
<tr ng-repeat="supp in $data | filter : filterObject |  filter : search">
_x000D_
_x000D_
_x000D_ Where "filterObject" is an object for searching an individual property and "Search" will search in every property globally.

~Atul

jQuery Ajax error handling, show custom exception messages

I believe the Ajax response handler uses the HTTP status code to check if there was an error.

So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.

I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.

I then set the Response.StatusCode to either 500 or 200 whether I had an error or not.

How can I get selector from jQuery object

Try this:

$("*").click(function(event){
    console.log($(event.handleObj.selector));
 });

How can a divider line be added in an Android RecyclerView?

In the October 2016 update, the support library v25.0.0 now has a default implementation of basic horizontal and vertical dividers available!

https://developer.android.com/reference/android/support/v7/widget/DividerItemDecoration.html

 recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Convert HTML to NSAttributedString in iOS

In iOS 7, UIKit added an initWithData:options:documentAttributes:error: method which can initialize an NSAttributedString using HTML, eg:

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                           NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                      documentAttributes:nil error:nil];

In Swift:

let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
        NSAttributedString.DocumentType.html]
let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
                                                          options: options,
                                                          documentAttributes: nil)

Sass calculate percent minus px

IF you know the width of the container, you could do like this:

#container
  width: #{200}px
  #element
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Turn off warnings and errors on PHP and MySQL

When you are sure your script is perfectly working, you can get rid of warning and notices like this: Put this line at the beginning of your PHP script:

error_reporting(E_ERROR);

Before that, when working on your script, I would advise you to properly debug your script so that all notice or warning disappear one by one.

So you should first set it as verbose as possible with:

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

UPDATE: how to log errors instead of displaying them

As suggested in the comments, the better solution is to log errors into a file so only the PHP developer sees the error messages, not the users.

A possible implementation is via the .htaccess file, useful if you don't have access to the php.ini file (source).

# Suppress PHP errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0

# Enable PHP error logging
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

# Prevent access to PHP error log
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

First char to upper case

Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.

Try this.

betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())

Creating a very simple linked list

Add a Node class.
Then add a LinkedList class to implement the linked list
Add a test class to execute the linked list

namespace LinkedListProject
{
    public class Node
    {
        public Node next;
        public object data;
    }

    public class MyLinkedList
    {
        Node head;
        public Node AddNodes(Object data)
        {
            Node node = new Node();

            if (node.next == null)
            {
                node.data = data;
                node.next = head;
                head = node;
            }
            else
            {
                while (node.next != null)
                    node = node.next;

                node.data = data;
                node.next = null;

            }
            return node;
        }

        public void printnodes()
        {
            Node current = head;
            while (current.next != null)
            {
                Console.WriteLine(current.data);
                current = current.next;
            }
            Console.WriteLine(current.data);
        }
    }


    [TestClass]
    public class LinkedListExample
    {
        MyLinkedList linkedlist = new MyLinkedList();
        [TestMethod]
        public void linkedlisttest()
        {
            linkedlist.AddNodes("hello");
            linkedlist.AddNodes("world");
            linkedlist.AddNodes("now");
            linkedlist.printnodes();
        }
    }
}

indexOf Case Sensitive?

Here's a version closely resembling Apache's StringUtils version:

public int indexOfIgnoreCase(String str, String searchStr) {
    return indexOfIgnoreCase(str, searchStr, 0);
}

public int indexOfIgnoreCase(String str, String searchStr, int fromIndex) {
    // https://stackoverflow.com/questions/14018478/string-contains-ignore-case/14018511
    if(str == null || searchStr == null) return -1;
    if (searchStr.length() == 0) return fromIndex;  // empty string found; use same behavior as Apache StringUtils
    final int endLimit = str.length() - searchStr.length() + 1;
    for (int i = fromIndex; i < endLimit; i++) {
        if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) return i;
    }
    return -1;
}

How to create multidimensional array

Declared without value assignment.

2 dimensions...

var arrayName = new Array(new Array());

3 dimensions...

var arrayName = new Array(new Array(new Array()));

Bash or KornShell (ksh)?

@foxxtrot

Actually, the standard shell is Bourne shell (sh). /bin/sh on Linux is actually bash, but if you're aiming for cross-platform scripts, you're better off sticking to features of the original Bourne shell or writing it in something like perl.

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.

String [] separado = line.split("\\*");

Android WebView style background-color:transparent ignored on android 2.2

Following code work for me, though i have multiple webviews and scrolling between them is bit sluggish.

v.setBackgroundColor(Color.TRANSPARENT);
Paint p = new Paint();
v.setLayerType(LAYER_TYPE_SOFTWARE, p);