Programs & Examples On #Openscenegraph

Openscenegraph is an OpenGL renderer and scene management API/toolkit.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

Okay, I think I know what you're looking for. It appears that GGT is a pretty good solution, as Reed Copsey suggested.

Personally, we rolled our own little library, because we deal with rational points a lot - lots of rational NURBS and Beziers.

It turns out that most 3D graphics libraries do computations with projective points that have no basis in projective math, because that's what gets you the answer you want. We ended up using Grassmann points, which have a solid theoretical underpinning and decreased the number of point types. Grassmann points are basically the same computations people are using now, with the benefit of a robust theory. Most importantly, it makes things clearer in our minds, so we have fewer bugs. Ron Goldman wrote a paper on Grassmann points in computer graphics called "On the Algebraic and Geometric Foundations of Computer Graphics".

Not directly related to your question, but an interesting read.

Make anchor link go some pixels above where it's linked to

Using only css and having no problems with covered and unclickable content before (the point of this is the pointer-events:none):

CSS

.anchored::before {
    content: '';
    display: block;
    position: relative;
    width: 0;
    height: 100px;
    margin-top: -100px;
}

HTML

<a href="#anchor">Click me!</a>
<div style="pointer-events:none;">
<p id="anchor" class="anchored">I should be 100px below where I currently am!</p>
</div>

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

How do I make an html link look like a button?

This worked for me. It looks like a button and behaves like a link. You can bookmark it for example.

<a href="mypage.aspx?param1=1" style="text-decoration:none;">
    <asp:Button PostBackUrl="mypage.aspx?param1=1" Text="my button-like link" runat="server" />
</a>

How can one change the timestamp of an old commit in Git?

Use git filter-branch with an env filter that sets GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for the specific hash of the commit you're looking to fix.

This will invalidate that and all future hashes.

Example:

If you wanted to change the dates of commit 119f9ecf58069b265ab22f1f97d2b648faf932e0, you could do so with something like this:

git filter-branch --env-filter \
    'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
     then
         export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
         export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
     fi'

Why aren't programs written in Assembly more often?

I'm sure there are many reasons, but two quick reasons I can think of are

  1. Assembly code is definitely harder to read (I'm positive its more time-consuming to write as well)
  2. When you have a huge team of developers working on a product, it is helpful to have your code divided into logical blocks and protected by interfaces.

Test or check if sheet exists

In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:

=ISREF(INDIRECT("SheetName!A1"))

This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.

Find the files that have been changed in last 24 hours

On GNU-compatible systems (i.e. Linux):

find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more

This will list files and directories that have been modified in the last 24 hours (-mtime 0). It will list them with the last modified time in a format that is both sortable and human-readable (%T+), followed by the file size (%s), followed by the full filename (%p), each separated by tabs (\t).

2>/dev/null throws away any stderr output, so that error messages don't muddy the waters; sort -r sorts the results by most recently modified first; and | more lists one page of results at a time.

SQL Server Creating a temp table for this query

IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL DROP TABLE #MyTempTable

CREATE TABLE #MyTempTable (SiteName varchar(50), BillingMonth varchar(10), Consumption float)

INSERT INTO #MyTempTable (SiteName, BillingMonth, Consumption)
SELECT  tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101)
AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects.......

Regular expression matching a multiline block of text

My preference.

lineIter= iter(aFile)
for line in lineIter:
    if line.startswith( ">" ):
         someVaryingText= line
         break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
    if len(line.strip()) == 0:
        break
    acids.append( line )

At this point you have someVaryingText as a string, and the acids as a list of strings. You can do "".join( acids ) to make a single string.

I find this less frustrating (and more flexible) than multiline regexes.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I encountered the same issue and lateron found out that, I have missed call to super.onCreate( savedInstanceState ); in onCreate() of FragmentActivity.

Count characters in textarea

We weren't happy with any of the purposed solutions.

So we've created a complete char counter solution for JQuery, built on top of jquery-jeditable. It's a textarea plugin extension that can count to both ways, displays a custom message, limits char count and also supports jquery-datatables.

You can test it right away on JSFiddle.

GitHub link: https://github.com/HippotecLTD/realworld_jquery_jeditable_charcount

Quick start

Add these lines to your HTML:

<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.jeditable.charcounter.realworld.min.js"></script>
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.charcounter.realworld.min.js"></script>

And then:

$("#myTextArea4").charCounter();

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Solution in ES6 for modern browsers and IE11 (with transpilation to ES5):

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
window.onkeydown = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            this.onEsc();
            break;
        //F1
        case 112:
            this.onF1();
            break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    //Returning false overrides default browser event
    return false;
};

Laravel - Forbidden You don't have permission to access / on this server

I met the same issue, then I do same as the solution of @lubat and my project work well. :D My virtualhost configuration:

<VirtualHost *:80>
     ServerName laravelht.vn
     DocumentRoot D:/Lavarel/HTPortal/public
     SetEnv APPLICATION_ENV "development"
     <Directory D:/Lavarel/HTPortal/public>
         DirectoryIndex index.php
         AllowOverride All
         Require all granted
         Order allow,deny
         Allow from all
     </Directory>
 </VirtualHost>

How to make an Android Spinner with initial text "Select One"?

For those using Xamarin, here is the C# equivalent to aaronvargas's answer above.

using Android.Content;
using Android.Database;
using Android.Views;
using Android.Widget;
using Java.Lang;

namespace MyNamespace.Droid
{ 
  public class NothingSelectedSpinnerAdapter : BaseAdapter, ISpinnerAdapter, IListAdapter
  {
    protected static readonly int EXTRA = 1;
    protected ISpinnerAdapter adapter;
    protected Context context;
    protected int nothingSelectedLayout;
    protected int nothingSelectedDropdownLayout;
    protected LayoutInflater layoutInflater;

    public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, Context context) : this(spinnerAdapter, nothingSelectedLayout, -1, context)
    {
    }

    public NothingSelectedSpinnerAdapter(ISpinnerAdapter spinnerAdapter, int nothingSelectedLayout, int nothingSelectedDropdownLayout, Context context)
    {
      this.adapter = spinnerAdapter;
      this.context = context;
      this.nothingSelectedLayout = nothingSelectedLayout;
      this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
      layoutInflater = LayoutInflater.From(context);
    }

    protected View GetNothingSelectedView(ViewGroup parent)
    {
      return layoutInflater.Inflate(nothingSelectedLayout, parent, false);
    }

    protected View GetNothingSelectedDropdownView(ViewGroup parent)
    {
      return layoutInflater.Inflate(nothingSelectedDropdownLayout, parent, false);
    }

    public override Object GetItem(int position)
    {
      return position == 0 ? null : adapter.GetItem(position - EXTRA);
    }

    public override long GetItemId(int position)
    {
      return position >= EXTRA ? adapter.GetItemId(position - EXTRA) : position - EXTRA;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
      // This provides the View for the Selected Item in the Spinner, not
      // the dropdown (unless dropdownView is not set).
      if (position == 0)
      {
        return GetNothingSelectedView(parent);
      }

      // Could re-use the convertView if possible.
      return this.adapter.GetView(position - EXTRA, null, parent);
    }

    public override int Count
    {
      get
      {
        int count = this.adapter.Count;
        return count == 0 ? 0 : count + EXTRA;
      }
    }

    public override View GetDropDownView(int position, View convertView, ViewGroup parent)
    {
      // Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
      // Spinner does not support multiple view types
      if (position == 0)
      {
        return nothingSelectedDropdownLayout == -1 ?
          new View(context) :
          GetNothingSelectedDropdownView(parent);
      }

      // Could re-use the convertView if possible, use setTag...
      return adapter.GetDropDownView(position - EXTRA, null, parent);
    }

    public override int GetItemViewType(int position)
    {
      return 0;
    }

    public override int ViewTypeCount => 1;

    public override bool HasStableIds => this.adapter.HasStableIds;

    public override bool IsEmpty => this.adapter.IsEmpty;

    public override void RegisterDataSetObserver(DataSetObserver observer)
    {
      adapter.RegisterDataSetObserver(observer);
    }

    public override void UnregisterDataSetObserver(DataSetObserver observer)
    {
      adapter.UnregisterDataSetObserver(observer);
    }

    public override bool AreAllItemsEnabled()
    {
      return false;
    }

    public override bool IsEnabled(int position)
    {
      return position > 0;
    }
  }
}

How do you programmatically update query params in react-router?

Example using react-router v4, redux-thunk and react-router-redux(5.0.0-alpha.6) package.

When user uses search feature, I want him to be able to send url link for same query to a colleague.

import { push } from 'react-router-redux';
import qs from 'query-string';

export const search = () => (dispatch) => {
    const query = { firstName: 'John', lastName: 'Doe' };

    //API call to retrieve records
    //...

    const searchString = qs.stringify(query);

    dispatch(push({
        search: searchString
    }))
}

How to see the changes between two commits without commits in-between?

Since Git 2.19, you can simply use:

git range-diff rev1...rev2 - compare two commit trees, starting by their common ancestor

or git range-diff rev1~..rev1 rev2~..rev2 - compare of changes introduced by 2 given commits

node.js: cannot find module 'request'

if some module you cant find, try with Static URI, for example:

var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");

This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2 Refer to: Blog of Ben Nadel

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Using the data.table package, which is fast (useful for larger datasets)

https://github.com/Rdatatable/data.table/wiki

library(data.table)
df2 <- setDT(df1)[, lapply(.SD, sum), by=.(year, month), .SDcols=c("x1","x2")]
setDF(df2) # convert back to dataframe

Using the plyr package

require(plyr)
df2 <- ddply(df1, c("year", "month"), function(x) colSums(x[c("x1", "x2")]))

Using summarize() from the Hmisc package (column headings are messy in my example though)

# need to detach plyr because plyr and Hmisc both have a summarize()
detach(package:plyr)
require(Hmisc)
df2 <- with(df1, summarize( cbind(x1, x2), by=llist(year, month), FUN=colSums))

Remove columns from dataframe where ALL values are NA

A handy base R option could be colMeans():

df[, colMeans(is.na(df)) != 1]

How to write a CSS hack for IE 11?

Use a combination of Microsoft specific CSS rules to filter IE11:

<!doctype html>
<html>
 <head>
  <title>IE10/11 Media Query Test</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <style>
    @media all and (-ms-high-contrast:none)
     {
     .foo { color: green } /* IE10 */
     *::-ms-backdrop, .foo { color: red } /* IE11 */
     }
  </style>
 </head>
 <body>
  <div class="foo">Hi There!!!</div>
 </body>
</html>

Filters such as this work because of the following:

When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well.

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
 <head>_x000D_
  <title>IE10/11 Media Query Test</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <style>_x000D_
    @media all and (-ms-high-contrast:none)_x000D_
     {_x000D_
     .foo { color: green } /* IE10 */_x000D_
     *::-ms-backdrop, .foo { color: red } /* IE11 */_x000D_
     }_x000D_
  </style>_x000D_
 </head>_x000D_
 <body>_x000D_
  <div class="foo">Hi There!!!</div>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

References

Combination of async function + await + setTimeout

If you would like to use the same kind of syntax as setTimeout you can write a helper function like this:

const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
    setTimeout(() => {
        cb();
        resolve();
    }, timeout);
});

You can then call it like so:

const doStuffAsync = async () => {
    await setAsyncTimeout(() => {
        // Do stuff
    }, 1000);

    await setAsyncTimeout(() => {
        // Do more stuff
    }, 500);

    await setAsyncTimeout(() => {
        // Do even more stuff
    }, 2000);
};

doStuffAsync();

I made a gist: https://gist.github.com/DaveBitter/f44889a2a52ad16b6a5129c39444bb57

How to use a PHP class from another file?

You can use include/include_once or require/require_once

require_once('class.php');

Alternatively, use autoloading by adding to page.php

<?php 
function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

$vars = new IUarts(); 
print($vars->data);    
?>

It also works adding that __autoload function in a lib that you include on every file like utils.php.

There is also this post that has a nice and different approach.

Efficient PHP auto-loading and naming strategies

Read data from SqlDataReader

I usually read data by data reader this way. just added a small example.

string connectionString = "Data Source=DESKTOP-2EV7CF4;Initial Catalog=TestDB;User ID=sa;Password=tintin11#";
string queryString = "Select * from EMP";

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
                        }
                    }
                    reader.Close();
                }
            }

Numpy Resize/Rescale Image

One-line numpy solution for downsampling (by 2):

smaller_img = bigger_img[::2, ::2]

And upsampling (by 2):

bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)

(this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))

Why are interface variables static and final by default?

(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.

The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:

public interface Actionable {
    public static boolean isActionable = false;

    public void performAction();
}

public NuclearAction implements Actionable {

    public void performAction() {
        // Code that depends on isActionable variable
        if (isActionable) {
            // Launch nuclear weapon!!!
        }
    }
}

Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:

public CleanAction implements Actionable  {

    public void performAction() {
        // Code that can alter isActionable state since it is not constant
        isActionable = true;
    }
}

If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).

Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.

Maven artifact and groupId naming

Weirdness is highly subjective, I just suggest to follow the official recommendation:

Guide to naming conventions on groupId, artifactId and version

  • groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.

    eg. org.apache.maven, org.apache.commons

    A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.

    eg. org.apache.maven, org.apache.maven.plugins, org.apache.maven.reporting

  • artifactId is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.

    eg. maven, commons-math

  • version if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.

    eg. 2.0, 2.0.1, 1.3.1

Refresh Page and Keep Scroll Position

This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.

Also added a data-confirm for prompting the user if they really want to do that..

Note: I'm using jQuery and js-cookie.js to store cookie info.

$(document).ready(function() {
    // make all links with data-confirm prompt the user first.
    $('[data-confirm]').on("click", function (e) {
        e.preventDefault();
        var msg = $(this).data("confirm");
        if(confirm(msg)==true) {
            var url = this.href;
            if(url.length>0) window.location = url;
            return true;
        }
        return false;
    });

    // on certain links save the scroll postion.
    $('.saveScrollPostion').on("click", function (e) {
        e.preventDefault();
        var currentYOffset = window.pageYOffset;  // save current page postion.
        Cookies.set('jumpToScrollPostion', currentYOffset);
        if(!$(this).attr("data-confirm")) {  // if there is no data-confirm on this link then trigger the click. else we have issues.
            var url = this.href;
            window.location = url;
            //$(this).trigger('click');  // continue with click event.
        }
    });

    // check if we should jump to postion.
    if(Cookies.get('jumpToScrollPostion') !== "undefined") {
        var jumpTo = Cookies.get('jumpToScrollPostion');
        window.scrollTo(0, jumpTo);
        Cookies.remove('jumpToScrollPostion');  // and delete cookie so we don't jump again.
    }
});

A example of using it like this.

<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>

How can I stop float left?

Sometimes clear will not work. Use float: none as an override

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

How can I get the max (or min) value in a vector?

If you want to use the function std::max_element(), the way you have to do it is:

double max = *max_element(vector.begin(), vector.end());
cout<<"Max value: "<<max<<endl;

I hope this can help.

Add items to comboBox in WPF

There are many ways to perform this task. Here is a simple one:

<Window x:Class="WPF_Demo1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     x:Name="TestWindow"
    Title="MainWindow" Height="500" Width="773">

<DockPanel LastChildFill="False">
    <StackPanel DockPanel.Dock="Top" Background="Red" Margin="2">
        <StackPanel Orientation="Horizontal" x:Name="spTopNav">
            <ComboBox x:Name="cboBox1" MinWidth="120"> <!-- Notice we have used x:Name to identify the object that we want to operate upon.-->
            <!--
                <ComboBoxItem Content="X"/>
                <ComboBoxItem Content="Y"/>
                <ComboBoxItem Content="Z"/>
            -->
            </ComboBox>
        </StackPanel>
    </StackPanel>
    <StackPanel DockPanel.Dock="Bottom" Background="Orange" Margin="2">
        <StackPanel Orientation="Horizontal" x:Name="spBottomNav">
        </StackPanel>
        <TextBlock Height="30" Foreground="White">Left Docked StackPanel 2</TextBlock>
    </StackPanel>
    <StackPanel MinWidth="200" DockPanel.Dock="Left" Background="Teal" Margin="2" x:Name="StackPanelLeft">
        <TextBlock  Foreground="White">Bottom Docked StackPanel Left</TextBlock>

    </StackPanel>
    <StackPanel DockPanel.Dock="Right" Background="Yellow" MinWidth="150" Margin="2" x:Name="StackPanelRight"></StackPanel>
    <Button Content="Button" Height="410" VerticalAlignment="Top" Width="75" x:Name="myButton" Click="myButton_Click"/>


</DockPanel>

</Window>      

Next, we have the C# code:

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        ComboBoxItem cboBoxItem = new ComboBoxItem(); // Create example instance of our desired type.
        Type type1 = cboBoxItem.GetType();
        object cboBoxItemInstance = Activator.CreateInstance(type1); // Construct an instance of that type.
        for (int i = 0; i < 12; i++)
        {
            string newName = "stringExample" + i.ToString();
           // Generate the objects from our list of strings.
            ComboBoxItem item = this.CreateComboBoxItem((ComboBoxItem)cboBoxItemInstance, "nameExample_" + newName, newName);
            cboBox1.Items.Add(item); // Add each newly constructed item to our NAMED combobox.
        }
    }
    private ComboBoxItem CreateComboBoxItem(ComboBoxItem myCbo, string content, string name)
    {
        Type type1 = myCbo.GetType();
        ComboBoxItem instance = (ComboBoxItem)Activator.CreateInstance(type1);
        // Here, we're using reflection to get and set the properties of the type.
        PropertyInfo Content = instance.GetType().GetProperty("Content", BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo Name = instance.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
        this.SetProperty<ComboBoxItem, String>(Content, instance, content);
        this.SetProperty<ComboBoxItem, String>(Name, instance, name);

        return instance;
        //PropertyInfo prop = type.GetProperties(rb1);
    }

Note: This is using reflection. If you'd like to learn more about the basics of reflection and why you might want to use it, this is a great introductory article:

If you'd like to learn more about how you might use reflection with WPF specifically, here are some resources:

And if you want to massively speed up the performance of reflection, it's best to use IL to do that, like this:

Annotation-specified bean name conflicts with existing, non-compatible bean def

I had the same issue. I solved it by using the following steps(Editor: IntelliJ):

  1. View -> Tool Windows -> Maven Project. Opens your projects in a sub-window.
  2. Click on the arrow next to your project.
  3. Click on the lifecycle.
  4. Click on clean.

Convert serial.read() into a useable string using Arduino?

Many great answers, here is my 2 cents with exact functionality as requested in the question.

Plus it should be a bit easier to read and debug.

Code is tested up to 128 chars of input.

Tested on Arduino uno r3 (Arduino IDE 1.6.8)

Functionality:

  • Turns Arduino onboard led (pin 13) on or off using serial command input.

Commands:

  • LED.ON
  • LED.OFF

Note: Remember to change baud rate based on your board speed.

// Turns Arduino onboard led (pin 13) on or off using serial command input.

// Pin 13, a LED connected on most Arduino boards.
int const LED = 13;

// Serial Input Variables
int intLoopCounter = 0;
String strSerialInput = "";

// the setup routine runs once when you press reset:
void setup() 
{
  // initialize the digital pin as an output.
  pinMode(LED, OUTPUT);

  // initialize serial port
  Serial.begin(250000); // CHANGE BAUD RATE based on the board speed.

  // initialized
  Serial.println("Initialized.");
}

// the loop routine runs over and over again forever:
void loop() 
{
  // Slow down a bit. 
  // Note: This may have to be increased for longer strings or increase the iteration in GetPossibleSerialData() function.
  delay(1);
  CheckAndExecuteSerialCommand();  
}

void CheckAndExecuteSerialCommand()
{
  //Get Data from Serial
  String serialData = GetPossibleSerialData();
  bool commandAccepted = false;

  if (serialData.startsWith("LED.ON"))
  {
    commandAccepted = true;
    digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  }
  else if  (serialData.startsWith("LED.OFF"))
  {
    commandAccepted = true;
    digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  }
  else if (serialData != "")
  {
    Serial.println();
    Serial.println("*** Command Failed ***");
    Serial.println("\t" + serialData);
    Serial.println();
    Serial.println();
    Serial.println("*** Invalid Command ***");
    Serial.println();
    Serial.println("Try:");
    Serial.println("\tLED.ON");
    Serial.println("\tLED.OFF");
    Serial.println();
  }

  if (commandAccepted)
  {
    Serial.println();
    Serial.println("*** Command Executed ***");
    Serial.println("\t" + serialData);
    Serial.println();
  }
}

String GetPossibleSerialData()
{
  String retVal;
  int iteration = 10; // 10 times the time it takes to do the main loop
  if (strSerialInput.length() > 0)
  {
    // Print the retreived string after looping 10(iteration) ex times
    if (intLoopCounter > strSerialInput.length() + iteration)
    {
        retVal = strSerialInput;
        strSerialInput = "";
        intLoopCounter = 0;
    } 
    intLoopCounter++;
  }

  return retVal;
}

void serialEvent()
{  
  while (Serial.available())
  {    
    strSerialInput.concat((char) Serial.read());
  } 
}

Quick unix command to display specific lines in the middle of a file?

with GNU-grep you could just say

grep --context=10 ...

Selecting only numeric columns from a data frame

Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names 
Names <- names(Numerical_variables)

How to append data to a json file?

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

When I try to set Base Memory around 4000MB (my pc have 8GB) I get the same error 'VT-x is disabled in the BIOS'. But when I reduce Base Memory to 2500MB it works and error is solved.

Extract every nth element of a vector

I think you are asking two things which are not necessarily the same

I want to extract every 6th element of the original

You can do this by indexing a sequence:

foo <- 1:120
foo[1:20*6]

I would like to create a vector in which each element is the i+6th element of another vector.

An easy way to do this is to supplement a logical factor with FALSEs until i+6:

foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1]   7  14  21  28  35  42  49  56  63  70  77  84  91  98 105 112 119

i <- 10
foo[1:(i+6)==(i+6)]
[1]  16  32  48  64  80  96 112

get all keys set in memcached

Base on @mu ? answer here. I've written a cache dump script.

The script dumps all the content of a memcached server. It's tested with Ubuntu 12.04 and a localhost memcached, so your milage may vary.

#!/usr/bin/env bash

echo 'stats items'  \
| nc localhost 11211  \
| grep -oe ':[0-9]*:'  \
| grep -oe '[0-9]*'  \
| sort  \
| uniq  \
| xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'

What it does, it goes through all the cache slabs and print 1000 entries of each.

Please be aware of certain limits of this script i.e. it may not scale for a 5GB cache server for example. But it's useful for debugging purposes on a local machine.

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

jQuery click event on radio button doesn't get fired

A different way

$("#inline_content input[name='type']").change(function () {
    if ($(this).val() == "walk_in" && $(this).is(":checked")) {
        $('#select-table > .roomNumber').attr('enabled', false);
    }
});

Demo - http://jsfiddle.net/cB6xV/

MSSQL Error 'The underlying provider failed on Open'

I was also facing the same issue. Now I have done it by removing the user name and password from the connection string.

What's the difference between django OneToOneField and ForeignKey?

OneToOneField: if second table is related with

table2_col1 = models.OneToOneField(table1,on_delete=models.CASCADE, related_name='table1_id')

table2 will contains only one record corresponding to table1's pk value, i.e table2_col1 will have unique value equal to pk of table

table2_col1 == models.ForeignKey(table1, on_delete=models.CASCADE, related_name='table1_id')

table2 may contains more than one record corresponding to table1's pk value.

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

How to avoid the "Circular view path" exception with Spring MVC test

This is how I solved this problem:

@Before
    public void setup() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/view/");
        viewResolver.setSuffix(".jsp");

        mockMvc = MockMvcBuilders.standaloneSetup(new HelpController())
                                 .setViewResolvers(viewResolver)
                                 .build();
    }

var functionName = function() {} vs function functionName() {}

I use the variable approach in my code for a very specific reason, the theory of which has been covered in an abstract way above, but an example might help some people like me, with limited JavaScript expertise.

I have code that I need to run with 160 independently-designed brandings. Most of the code is in shared files, but branding-specific stuff is in a separate file, one for each branding.

Some brandings require specific functions, and some do not. Sometimes I have to add new functions to do new branding-specific things. I am happy to change the shared coded, but I don't want to have to change all 160 sets of branding files.

By using the variable syntax, I can declare the variable (a function pointer essentially) in the shared code and either assign a trivial stub function, or set to null.

The one or two brandings that need a specific implementation of the function can then define their version of the function and assign this to the variable if they want, and the rest do nothing. I can test for a null function before I execute it in the shared code.

From people's comments above, I gather it may be possible to redefine a static function too, but I think the variable solution is nice and clear.

How to get controls in WPF to fill available space?

Each control deriving from Panel implements distinct layout logic performed in Measure() and Arrange():

  • Measure() determines the size of the panel and each of its children
  • Arrange() determines the rectangle where each control renders

The last child of the DockPanel fills the remaining space. You can disable this behavior by setting the LastChild property to false.

The StackPanel asks each child for its desired size and then stacks them. The stack panel calls Measure() on each child, with an available size of Infinity and then uses the child's desired size.

A Grid occupies all available space, however, it will set each child to their desired size and then center them in the cell.

You can implement your own layout logic by deriving from Panel and then overriding MeasureOverride() and ArrangeOverride().

See this article for a simple example.

How to view data saved in android database(SQLite)?

I recommend the firefox plugin(SQLLite Manager) if you always use firefox.

Here is the link

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

Array vs ArrayList in performance

It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.

Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.

Jquery how to find an Object by attribute in an Array

copied from polyfill Array.prototype.find code of Array.find, and added the array as first parameter.

you can pass the search term as predicate function

_x000D_
_x000D_
// Example_x000D_
var listOfObjects = [{key: "1", value: "one"}, {key: "2", value: "two"}]_x000D_
var result = findInArray(listOfObjects, function(element) {_x000D_
  return element.key == "1";_x000D_
});_x000D_
console.log(result);_x000D_
_x000D_
// the function you want_x000D_
function findInArray(listOfObjects, predicate) {_x000D_
      if (listOfObjects == null) {_x000D_
        throw new TypeError('listOfObjects is null or not defined');_x000D_
      }_x000D_
_x000D_
      var o = Object(listOfObjects);_x000D_
_x000D_
      var len = o.length >>> 0;_x000D_
_x000D_
      if (typeof predicate !== 'function') {_x000D_
        throw new TypeError('predicate must be a function');_x000D_
      }_x000D_
_x000D_
      var thisArg = arguments[1];_x000D_
_x000D_
      var k = 0;_x000D_
_x000D_
      while (k < len) {_x000D_
        var kValue = o[k];_x000D_
        if (predicate.call(thisArg, kValue, k, o)) {_x000D_
          return kValue;_x000D_
        }_x000D_
        k++;_x000D_
      }_x000D_
_x000D_
      return undefined;_x000D_
}
_x000D_
_x000D_
_x000D_

throwing exceptions out of a destructor

Set an alarm event. Typically alarm events are better form of notifying failure while cleaning up objects

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

How to verify element present or visible in selenium 2 (Selenium WebDriver)

You could try something like:

    WebElement rxBtn = driver.findElement(By.className("icon-rx"));
    WebElement otcBtn = driver.findElement(By.className("icon-otc"));
    WebElement herbBtn = driver.findElement(By.className("icon-herb"));

    Assert.assertEquals(true, rxBtn.isDisplayed());
    Assert.assertEquals(true, otcBtn.isDisplayed());
    Assert.assertEquals(true, herbBtn.isDisplayed());

This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert whether or not they are displayed. This is using TestNG Assertions.

Access Https Rest Service using Spring RestTemplate

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File(keyStoreFile)),
  keyStorePassword.toCharArray());

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
  new SSLContextBuilder()
    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
    .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
    .build(),
    NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
  socketFactory).build();

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
  httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
MyRecord record = restTemplate.getForObject(uri, MyRecord.class);
LOG.debug(record.toString());

MySQL date formats - difficulty Inserting a date

Put the date in single quotes and move the parenthesis (after the 'yes') to the end:

INSERT INTO custorder 
  VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
                        ^                                     ^
---parenthesis removed--|                and added here ------|

But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals

INSERT INTO custorder 
  VALUES ('Kevin', 'yes', '2012-01-01') ;

How do I discover memory usage of my application in Android?

Note that memory usage on modern operating systems like Linux is an extremely complicated and difficult to understand area. In fact the chances of you actually correctly interpreting whatever numbers you get is extremely low. (Pretty much every time I look at memory usage numbers with other engineers, there is always a long discussion about what they actually mean that only results in a vague conclusion.)

Note: we now have much more extensive documentation on Managing Your App's Memory that covers much of the material here and is more up-to-date with the state of Android.

First thing is to probably read the last part of this article which has some discussion of how memory is managed on Android:

Service API changes starting with Android 2.0

Now ActivityManager.getMemoryInfo() is our highest-level API for looking at overall memory usage. This is mostly there to help an application gauge how close the system is coming to having no more memory for background processes, thus needing to start killing needed processes like services. For pure Java applications, this should be of little use, since the Java heap limit is there in part to avoid one app from being able to stress the system to this point.

Going lower-level, you can use the Debug API to get raw kernel-level information about memory usage: android.os.Debug.MemoryInfo

Note starting with 2.0 there is also an API, ActivityManager.getProcessMemoryInfo, to get this information about another process: ActivityManager.getProcessMemoryInfo(int[])

This returns a low-level MemoryInfo structure with all of this data:

    /** The proportional set size for dalvik. */
    public int dalvikPss;
    /** The private dirty pages used by dalvik. */
    public int dalvikPrivateDirty;
    /** The shared dirty pages used by dalvik. */
    public int dalvikSharedDirty;

    /** The proportional set size for the native heap. */
    public int nativePss;
    /** The private dirty pages used by the native heap. */
    public int nativePrivateDirty;
    /** The shared dirty pages used by the native heap. */
    public int nativeSharedDirty;

    /** The proportional set size for everything else. */
    public int otherPss;
    /** The private dirty pages used by everything else. */
    public int otherPrivateDirty;
    /** The shared dirty pages used by everything else. */
    public int otherSharedDirty;

But as to what the difference is between Pss, PrivateDirty, and SharedDirty... well now the fun begins.

A lot of memory in Android (and Linux systems in general) is actually shared across multiple processes. So how much memory a processes uses is really not clear. Add on top of that paging out to disk (let alone swap which we don't use on Android) and it is even less clear.

Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM.

The Pss number is a metric the kernel computes that takes into account memory sharing -- basically each page of RAM in a process is scaled by a ratio of the number of other processes also using that page. This way you can (in theory) add up the pss across all processes to see the total RAM they are using, and compare pss between processes to get a rough idea of their relative weight.

The other interesting metric here is PrivateDirty, which is basically the amount of RAM inside the process that can not be paged to disk (it is not backed by the same data on disk), and is not shared with any other processes. Another way to look at this is the RAM that will become available to the system when that process goes away (and probably quickly subsumed into caches and other uses of it).

That is pretty much the SDK APIs for this. However there is more you can do as a developer with your device.

Using adb, there is a lot of information you can get about the memory use of a running system. A common one is the command adb shell dumpsys meminfo which will spit out a bunch of information about the memory use of each Java process, containing the above info as well as a variety of other things. You can also tack on the name or pid of a single process to see, for example adb shell dumpsys meminfo system give me the system process:

** MEMINFO in pid 890 [system] **
                    native   dalvik    other    total
            size:    10940     7047      N/A    17987
       allocated:     8943     5516      N/A    14459
            free:      336     1531      N/A     1867
           (Pss):     4585     9282    11916    25783
  (shared dirty):     2184     3596      916     6696
    (priv dirty):     4504     5956     7456    17916

 Objects
           Views:      149        ViewRoots:        4
     AppContexts:       13       Activities:        0
          Assets:        4    AssetManagers:        4
   Local Binders:      141    Proxy Binders:      158
Death Recipients:       49
 OpenSSL Sockets:        0

 SQL
            heap:      205          dbFiles:        0
       numPagers:        0   inactivePageKB:        0
    activePageKB:        0

The top section is the main one, where size is the total size in address space of a particular heap, allocated is the kb of actual allocations that heap thinks it has, free is the remaining kb free the heap has for additional allocations, and pss and priv dirty are the same as discussed before specific to pages associated with each of the heaps.

If you just want to look at memory usage across all processes, you can use the command adb shell procrank. Output of this on the same system looks like:

  PID      Vss      Rss      Pss      Uss  cmdline
  890   84456K   48668K   25850K   21284K  system_server
 1231   50748K   39088K   17587K   13792K  com.android.launcher2
  947   34488K   28528K   10834K    9308K  com.android.wallpaper
  987   26964K   26956K    8751K    7308K  com.google.process.gapps
  954   24300K   24296K    6249K    4824K  com.android.phone
  948   23020K   23016K    5864K    4748K  com.android.inputmethod.latin
  888   25728K   25724K    5774K    3668K  zygote
  977   24100K   24096K    5667K    4340K  android.process.acore
...
   59     336K     332K      99K      92K  /system/bin/installd
   60     396K     392K      93K      84K  /system/bin/keystore
   51     280K     276K      74K      68K  /system/bin/servicemanager
   54     256K     252K      69K      64K  /system/bin/debuggerd

Here the Vss and Rss columns are basically noise (these are the straight-forward address space and RAM usage of a process, where if you add up the RAM usage across processes you get an ridiculously large number).

Pss is as we've seen before, and Uss is Priv Dirty.

Interesting thing to note here: Pss and Uss are slightly (or more than slightly) different than what we saw in meminfo. Why is that? Well procrank uses a different kernel mechanism to collect its data than meminfo does, and they give slightly different results. Why is that? Honestly I haven't a clue. I believe procrank may be the more accurate one... but really, this just leave the point: "take any memory info you get with a grain of salt; often a very large grain."

Finally there is the command adb shell cat /proc/meminfo that gives a summary of the overall memory usage of the system. There is a lot of data here, only the first few numbers worth discussing (and the remaining ones understood by few people, and my questions of those few people about them often resulting in conflicting explanations):

MemTotal:         395144 kB
MemFree:          184936 kB
Buffers:             880 kB
Cached:            84104 kB
SwapCached:            0 kB

MemTotal is the total amount of memory available to the kernel and user space (often less than the actual physical RAM of the device, since some of that RAM is needed for the radio, DMA buffers, etc).

MemFree is the amount of RAM that is not being used at all. The number you see here is very high; typically on an Android system this would be only a few MB, since we try to use available memory to keep processes running

Cached is the RAM being used for filesystem caches and other such things. Typical systems will need to have 20MB or so for this to avoid getting into bad paging states; the Android out of memory killer is tuned for a particular system to make sure that background processes are killed before the cached RAM is consumed too much by them to result in such paging.

Set CFLAGS and CXXFLAGS options using CMake

You need to set the flags after the project command in your CMakeLists.txt.

Also, if you're calling include(${QT_USE_FILE}) or add_definitions(${QT_DEFINITIONS}), you should include these set commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")

Create a list with initial capacity in Python

The Pythonic way for this is:

x = [None] * numElements

Or whatever default value you wish to prepopulate with, e.g.

bottles = [Beer()] * 99
sea = [Fish()] * many
vegetarianPizzas = [None] * peopleOrderingPizzaNotQuiche

(Caveat Emptor: The [Beer()] * 99 syntax creates one Beer and then populates an array with 99 references to the same single instance)

Python's default approach can be pretty efficient, although that efficiency decays as you increase the number of elements.

Compare

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # Millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    result = []
    i = 0
    while i < Elements:
        result.append(i)
        i += 1

def doAllocate():
    result = [None] * Elements
    i = 0
    while i < Elements:
        result[i] = i
        i += 1

def doGenerator():
    return list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        x = 0
        while x < Iterations:
            fn()
            x += 1


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

with

#include <vector>
typedef std::vector<unsigned int> Vec;

static const unsigned int Elements = 100000;
static const unsigned int Iterations = 144;

void doAppend()
{
    Vec v;
    for (unsigned int i = 0; i < Elements; ++i) {
        v.push_back(i);
    }
}

void doReserve()
{
    Vec v;
    v.reserve(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v.push_back(i);
    }
}

void doAllocate()
{
    Vec v;
    v.resize(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v[i] = i;
    }
}

#include <iostream>
#include <chrono>
using namespace std;

void test(const char* name, void(*fn)(void))
{
    cout << name << ": ";

    auto start = chrono::high_resolution_clock::now();
    for (unsigned int i = 0; i < Iterations; ++i) {
        fn();
    }
    auto end = chrono::high_resolution_clock::now();

    auto elapsed = end - start;
    cout << chrono::duration<double, milli>(elapsed).count() << "ms\n";
}

int main()
{
    cout << "Elements: " << Elements << ", Iterations: " << Iterations << '\n';

    test("doAppend", doAppend);
    test("doReserve", doReserve);
    test("doAllocate", doAllocate);
}

On my Windows 7 Core i7, 64-bit Python gives

Elements: 100000, Iterations: 144
doAppend: 3587.204933ms
doAllocate: 2701.154947ms
doGenerator: 1721.098185ms

While C++ gives (built with Microsoft Visual C++, 64-bit, optimizations enabled)

Elements: 100000, Iterations: 144
doAppend: 74.0042ms
doReserve: 27.0015ms
doAllocate: 5.0003ms

C++ debug build produces:

Elements: 100000, Iterations: 144
doAppend: 2166.12ms
doReserve: 2082.12ms
doAllocate: 273.016ms

The point here is that with Python you can achieve a 7-8% performance improvement, and if you think you're writing a high-performance application (or if you're writing something that is used in a web service or something) then that isn't to be sniffed at, but you may need to rethink your choice of language.

Also, the Python code here isn't really Python code. Switching to truly Pythonesque code here gives better performance:

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    for x in range(Iterations):
        result = []
        for i in range(Elements):
            result.append(i)

def doAllocate():
    for x in range(Iterations):
        result = [None] * Elements
        for i in range(Elements):
            result[i] = i

def doGenerator():
    for x in range(Iterations):
        result = list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        fn()


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

Which gives

Elements: 100000, Iterations: 144
doAppend: 2153.122902ms
doAllocate: 1346.076965ms
doGenerator: 1614.092112ms

(in 32-bit, doGenerator does better than doAllocate).

Here the gap between doAppend and doAllocate is significantly larger.

Obviously, the differences here really only apply if you are doing this more than a handful of times or if you are doing this on a heavily loaded system where those numbers are going to get scaled out by orders of magnitude, or if you are dealing with considerably larger lists.

The point here: Do it the Pythonic way for the best performance.

But if you are worrying about general, high-level performance, Python is the wrong language. The most fundamental problem being that Python function calls has traditionally been up to 300x slower than other languages due to Python features like decorators, etc. (PythonSpeed/PerformanceTips, Data Aggregation).

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}

How do I check if a file exists in Java?

Simple example with good coding practices and covering all cases :

 private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
        File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
        if (f.exists()) {
            throw new FileAlreadyExistsException(f.getAbsolutePath());
        } else {
            try {
                URL u = new URL(url);
                FileUtils.copyURLToFile(u, f);
            } catch (MalformedURLException ex) {
                Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

Reference and more examples at

https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations

What is the default access modifier in Java?

From a book named OCA Java SE 7 Programmer I:

The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package.

What is the most effective way for float and double comparison?

Found another interesting implementation on: https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon

#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <algorithm>



template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
    almost_equal(T x, T y, int ulp)
{
    // the machine epsilon has to be scaled to the magnitude of the values used
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::fabs(x-y) <= std::numeric_limits<T>::epsilon() * std::fabs(x+y) * ulp
        // unless the result is subnormal
        || std::fabs(x-y) < std::numeric_limits<T>::min();
}

int main()
{
    double d1 = 0.2;
    double d2 = 1 / std::sqrt(5) / std::sqrt(5);
    std::cout << std::fixed << std::setprecision(20) 
        << "d1=" << d1 << "\nd2=" << d2 << '\n';

    if(d1 == d2)
        std::cout << "d1 == d2\n";
    else
        std::cout << "d1 != d2\n";

    if(almost_equal(d1, d2, 2))
        std::cout << "d1 almost equals d2\n";
    else
        std::cout << "d1 does not almost equal d2\n";
}

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

I found that this error can now also occur when using the wrong signing config. As described here, Android 7.0 introduces a new signature scheme, V2. The V2 scheme signs the entire APK rather than just the JAR, as is done in the V1 scheme. If you sign with only V2, and attempt to install on a pre-7.0 target, you'll get this error since the JARs themselves are not signed and the pre-7.0 PackageManager cannot detect the presence of the V2 APK signature.

To be compatible with all target systems, make sure the APK is signed with both schemes by checking both signature version boxes in Android Studio's Generate Signed APK dialog as shown here:

enter image description here

If only 7.0 targets are anticipated, then there is no need to include the V1 signature.

Equivalent of explode() to work with strings in MySQL

You can use stored procedure in this way..

DELIMITER |

CREATE PROCEDURE explode( pDelim VARCHAR(32), pStr TEXT)                                
BEGIN                                
  DROP TABLE IF EXISTS temp_explode;                                
  CREATE TEMPORARY TABLE temp_explode (id INT AUTO_INCREMENT PRIMARY KEY NOT NULL, word VARCHAR(40));                                
  SET @sql := CONCAT('INSERT INTO temp_explode (word) VALUES (', REPLACE(QUOTE(pStr), pDelim, '\'), (\''), ')');                                
  PREPARE myStmt FROM @sql;                                
  EXECUTE myStmt;                                
END |   

DELIMITER ;
  • example call:

     SET @str  = "The quick brown fox jumped over the lazy dog"; 
     SET @delim = " "; 
    
    CALL explode(@delim,@str);
    SELECT id,word FROM temp_explode;
    

Replace transparency in PNG images with white background

Non-command line option: open the PNG file in Windows Paint and click Save.

Private properties in JavaScript ES6 classes

we can emulate a private property of a class using getter and setter.

eg 1

class FootballClub {
    constructor (cname, cstadium, ccurrentmanager) {
        this.name = cname;
        this._stadium  = cstadium;  //  we will treat this prop as private and give getter and setter for this.
        this.currmanager = ccurrentmanager;
    }

    get stadium( ) {
        return this._stadium.toUpperCase();
    }

}

let club = new FootballClub("Arsenal", "Emirates" , "Arteta")
console.log(club);
//FootballClub {
//    name: 'Arsenal',
//    _stadium: 'Emirates',
//    currmanager: 'Arteta'
//  }
console.log( club.stadium ); // EMIRATES
club.stadium = "Highbury"; // TypeError: Cannot set property stadium of #<FootballClub> which has only a getter

In the above example we have not given a setter method for stadium and thus we are not able to set a new value for this. In the next eg a setter is added for stadium

eg 2

class FootballClub {
    constructor (cname, cstadium, ccurrentmanager) {
        this.name = cname;
        this._stadium  = cstadium;  //  we will treat this prop as private and give getter and setter for this.
        this.currmanager = ccurrentmanager;
    }

    get stadium( ) {
        return this._stadium.toUpperCase();
    }

    set stadium(val) {
       this._stadium = val;
    }
}

let club = new FootballClub("Arsenal", "Emirates" , "Arteta")
console.log(club.stadium); // EMIRATES
club.stadium = "Emirates Stadium";
console.log(club.stadium); // EMIRATES STADIUM

How to get the first column of a pandas DataFrame as a Series?

You can get the first column as a Series by following code:

x[x.columns[0]]

jQuery click event not working after adding class

.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

$(document).on('click', "a.tabclick", function() {

This syntax will work for delegated events

.on()

Convert int to char in java

Nobody has answered the real "question" here: you ARE converting int to char correctly; in the ASCII table a decimal value of 01 is "start of heading", a non-printing character. Try looking up an ASCII table and converting an int value between 33 and 7E; that will give you characters to look at.

Make Vim show ALL white spaces as a character

you can also highlight the spaces (replacing the spaces with a block):

:%s/ /¦/g

(before writing undo it)

How to get screen width without (minus) scrollbar?

None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.

How can I fix "Design editor is unavailable until a successful build" error?

Go online before starting android studio. Then go file->New project Follow onscreen steps. Then wait It will download the necessary files over internet. And that should fix it.

How to convert an Array to a Set in Java

Like this:

Set<T> mySet = new HashSet<>(Arrays.asList(someArray));

In Java 9+, if unmodifiable set is ok:

Set<T> mySet = Set.of(someArray);

In Java 10+, the generic type parameter can be inferred from the arrays component type:

var mySet = Set.of(someArray);

Make absolute positioned div expand parent div height

I came up with another solution, which I don't love but gets the job done.

Basically duplicate the child elements in such a way that the duplicates are not visible.

<div id="parent">
    <div class="width-calc">
        <div class="child1"></div>
        <div class="child2"></div>
    </div>

    <div class="child1"></div>
    <div class="child2"></div>
</div>

CSS:

.width-calc {
    height: 0;
    overflow: hidden;
}

If those child elements contain little markup, then the impact will be small.

How can I push a specific commit to a remote, and not previous commits?

You could also, in another directory:

  • git clone [your repository]
  • Overwrite the .git directory in your original repository with the .git directory of the repository you just cloned right now.
  • git add and git commit your original

What are the differences between a pointer variable and a reference variable in C++?

The direct answer

What is a reference in C++? Some specific instance of type that is not an object type.

What is a pointer in C++? Some specific instance of type that is an object type.

From the ISO C++ definition of object type:

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not cv void.

It may be important to know, object type is a top-level category of the type universe in C++. Reference is also a top-level category. But pointer is not.

Pointers and references are mentioned together in the context of compound type. This is basically due to the nature of the declarator syntax inherited from (and extended) C, which has no references. (Besides, there are more than one kind of declarator of references since C++ 11, while pointers are still "unityped": &+&& vs. *.) So drafting a language specific by "extension" with similar style of C in this context is somewhat reasonable. (I will still argue that the syntax of declarators wastes the syntactic expressiveness a lot, makes both human users and implementations frustrating. Thus, all of them are not qualified to be built-in in a new language design. This is a totally different topic about PL design, though.)

Otherwise, it is insignificant that pointers can be qualified as a specific sorts of types with references together. They simply share too few common properties besides the syntax similarity, so there is no need to put them together in most cases.

Note the statements above only mentions "pointers" and "references" as types. There are some interested questions about their instances (like variables). There also come too many misconceptions.

The differences of the top-level categories can already reveal many concrete differences not tied to pointers directly:

  • Object types can have top-level cv qualifiers. References cannot.
  • Variable of object types do occupy storage as per the abstract machine semantics. Reference do not necessary occupy storage (see the section about misconceptions below for details).
  • ...

A few more special rules on references:

  • Compound declarators are more restrictive on references.
  • References can collapse.
    • Special rules on && parameters (as the "forwarding references") based on reference collapsing during template parameter deduction allow "perfect forwarding" of parameters.
  • References have special rules in initialization. The lifetime of variable declared as a reference type can be different to ordinary objects via extension.
    • BTW, a few other contexts like initialization involving std::initializer_list follows some similar rules of reference lifetime extension. It is another can of worms.
  • ...

The misconceptions

Syntactic sugar

I know references are syntactic sugar, so code is easier to read and write.

Technically, this is plain wrong. References are not syntactic sugar of any other features in C++, because they cannot be exactly replaced by other features without any semantic differences.

(Similarly, lambda-expressions are not syntactic sugar of any other features in C++ because it cannot be precisely simulated with "unspecified" properties like the declaration order of the captured variables, which may be important because the initialization order of such variables can be significant.)

C++ only has a few kinds of syntactic sugars in this strict sense. One instance is (inherited from C) the built-in (non-overloaded) operator [], which is defined exactly having same semantic properties of specific forms of combination over built-in operator unary * and binary +.

Storage

So, a pointer and a reference both use the same amount of memory.

The statement above is simply wrong. To avoid such misconceptions, look at the ISO C++ rules instead:

From [intro.object]/1:

... An object occupies a region of storage in its period of construction, throughout its lifetime, and in its period of destruction. ...

From [dcl.ref]/4:

It is unspecified whether or not a reference requires storage.

Note these are semantic properties.

Pragmatics

Even that pointers are not qualified enough to be put together with references in the sense of the language design, there are still some arguments making it debatable to make choice between them in some other contexts, for example, when making choices on parameter types.

But this is not the whole story. I mean, there are more things than pointers vs references you have to consider.

If you don't have to stick on such over-specific choices, in most cases the answer is short: you do not have the necessity to use pointers, so you don't. Pointers are usually bad enough because they imply too many things you don't expect and they will rely on too many implicit assumptions undermining the maintainability and (even) portability of the code. Unnecessarily relying on pointers is definitely a bad style and it should be avoided in the sense of modern C++. Reconsider your purpose and you will finally find that pointer is the feature of last sorts in most cases.

  • Sometimes the language rules explicitly require specific types to be used. If you want to use these features, obey the rules.
    • Copy constructors require specific types of cv-& reference type as the 1st parameter type. (And usually it should be const qualified.)
    • Move constructors require specific types of cv-&& reference type as the 1st parameter type. (And usually there should be no qualifiers.)
    • Specific overloads of operators require reference or non reference types. For example:
      • Overloaded operator= as special member functions requires reference types similar to 1st parameter of copy/move constructors.
      • Postfix ++ requires dummy int.
      • ...
  • If you know pass-by-value (i.e. using non-reference types) is sufficient, use it directly, particularly when using an implementation supporting C++17 mandated copy elision. (Warning: However, to exhaustively reason about the necessity can be very complicated.)
  • If you want to operate some handles with ownership, use smart pointers like unique_ptr and shared_ptr (or even with homebrew ones by yourself if you require them to be opaque), rather than raw pointers.
  • If you are doing some iterations over a range, use iterators (or some ranges which are not provided by the standard library yet), rather than raw pointers unless you are convinced raw pointers will do better (e.g. for less header dependencies) in very specific cases.
  • If you know pass-by-value is sufficient and you want some explicit nullable semantics, use wrapper like std::optional, rather than raw pointers.
  • If you know pass-by-value is not ideal for the reasons above, and you don't want nullable semantics, use {lvalue, rvalue, forwarding}-references.
  • Even when you do want semantics like traditional pointer, there are often something more appropriate, like observer_ptr in Library Fundamental TS.

The only exceptions cannot be worked around in the current language:

  • When you are implementing smart pointers above, you may have to deal with raw pointers.
  • Specific language-interoperation routines require pointers, like operator new. (However, cv-void* is still quite different and safer compared to the ordinary object pointers because it rules out unexpected pointer arithmetics unless you are relying on some non conforming extension on void* like GNU's.)
  • Function pointers can be converted from lambda expressions without captures, while function references cannot. You have to use function pointers in non-generic code for such cases, even you deliberately do not want nullable values.

So, in practice, the answer is so obvious: when in doubt, avoid pointers. You have to use pointers only when there are very explicit reasons that nothing else is more appropriate. Except a few exceptional cases mentioned above, such choices are almost always not purely C++-specific (but likely to be language-implementation-specific). Such instances can be:

  • You have to serve to old-style (C) APIs.
  • You have to meet the ABI requirements of specific C++ implementations.
  • You have to interoperate at runtime with different language implementations (including various assemblies, language runtime and FFI of some high-level client languages) based on assumptions of specific implementations.
  • You have to improve efficiency of the translation (compilation & linking) in some extreme cases.
  • You have to avoid symbol bloat in some extreme cases.

Language neutrality caveats

If you come to see the question via some Google search result (not specific to C++), this is very likely to be the wrong place.

References in C++ is quite "odd", as it is essentially not first-class: they will be treated as the objects or the functions being referred to so they have no chance to support some first-class operations like being the left operand of the member access operator independently to the type of the referred object. Other languages may or may not have similar restrictions on their references.

References in C++ will likely not preserve the meaning across different languages. For example, references in general do not imply nonnull properties on values like they in C++, so such assumptions may not work in some other languages (and you will find counterexamples quite easily, e.g. Java, C#, ...).

There can still be some common properties among references in different programming languages in general, but let's leave it for some other questions in SO.

(A side note: the question may be significant earlier than any "C-like" languages are involved, like ALGOL 68 vs. PL/I.)

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

The problem with the other answers is, that some characters like numbers or punctuation also return true when checked for lowercase/uppercase.

I found this to work very well for it:

function isLowerCase(str)
{
    return str == str.toLowerCase() && str != str.toUpperCase();
}

This will work for punctuation, numbers and letters:

assert(isLowerCase("a"))
assert(!isLowerCase("Ü"))
assert(!isLowerCase("4"))
assert(!isLowerCase("_"))

To check one letter just call it using isLowerCase(str[charIndex])

CSS Box Shadow - Top and Bottom Only

As Kristian has pointed out, good control over z-values will often solve your problems.

If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.

I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:

box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;

This will give you some control over the "amount" of shadow in each direction.

Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.

Hope this was what you were looking for!

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

In my case the issue was the Google services gradle plugin with the following line in the gradle file:

apply plugin: 'com.google.gms.google-services'

Removing this resolved the issue

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

HTML

<form id="some_form">
<!-- some form elements -->
</form>

and jquery

$("#some_form").reset();

How to fix syntax error, unexpected T_IF error in php?

PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if that comes next.

You'll get used to it :)

Escaping single quote in PHP when inserting into MySQL

mysql_real_escape_string() or str_replace() function will help you to solve your problem.

http://phptutorial.co.in/php-echo-print/

How do I replace multiple spaces with a single space in C#?

string xyz = "1   2   3   4   5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

Convert Uri to String and String to Uri

Try this to convert string to uri

String mystring="Hello"
Uri myUri = Uri.parse(mystring);

Uri to String

Uri uri;
String uri_to_string;
uri_to_string= uri.toString();

iOS 7 - Failing to instantiate default view controller

I get this error when I change the the storyboard file name "Main.storyboard" TO: "XXX.storyboard"

The solution for me was:

  • Product->Clean
  • CHANGE: Supporting Files -> info.plist -> Main storyboard file base name -> Main TO: XXX

Good Luck

Git: list only "untracked" files (also, custom commands)

I know its an old question, but in terms of listing untracked files I thought I would add another one which also lists untracked folders:

You can used the git clean operation with -n (dry run) to show you which files it will remove (including the .gitignore files) by:

git clean -xdn

This has the advantage of showing all files and all folders that are not tracked. Parameters:

  • x - Shows all untracked files (including ignored by git and others, like build output etc...)
  • d - show untracked directories
  • n - and most importantly! - dryrun, i.e. don't actually delete anything, just use the clean mechanism to display the results.

It can be a little bit unsafe to do it like this incase you forget the -n. So I usually alias it in git config.

what is right way to do API call in react js?

I would like you to have a look at redux http://redux.js.org/index.html

They have very well defined way of handling async calls ie API calls, and instead of using jQuery for API calls, I would like to recommend using fetch or request npm packages, fetch is currently supported by modern browsers, but a shim is also available for server side.

There is also this another amazing package superagent, which has alot many options when making an API request and its very easy to use.

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

Convert seconds to HH-MM-SS with JavaScript?

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

Example:

_x000D_
_x000D_
let totalSeconds = 28565;_x000D_
let hours = Math.floor(totalSeconds / 3600);_x000D_
totalSeconds %= 3600;_x000D_
let minutes = Math.floor(totalSeconds / 60);_x000D_
let seconds = totalSeconds % 60;_x000D_
_x000D_
console.log("hours: " + hours);_x000D_
console.log("minutes: " + minutes);_x000D_
console.log("seconds: " + seconds);_x000D_
_x000D_
// If you want strings with leading zeroes:_x000D_
minutes = String(minutes).padStart(2, "0");_x000D_
hours = String(hours).padStart(2, "0");_x000D_
seconds = String(seconds).padStart(2, "0");_x000D_
console.log(hours + ":" + minutes + ":" + seconds);
_x000D_
_x000D_
_x000D_

python inserting variable string as file name

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

How to execute two mysql queries as one in PHP/MYSQL?

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

Xcode: failed to get the task for process

If anyone is having this issue but is sure they have their certificates and code signing correctly set up, check the capabilities tab when you click on the project (i.e. next to build settings tab, build phases tab, etc).

In my case there were broken links for Game Center and In-App Purchases that needed fixing (by clicking the "fix me" buttons) to solve this issue.

Bash: Syntax error: redirection unexpected

Does your script reference /bin/bash or /bin/sh in its hash bang line? The default system shell in Ubuntu is dash, not bash, so if you have #!/bin/sh then your script will be using a different shell than you expect. Dash does not have the <<< redirection operator.

Where does Chrome store cookies?

You can find a solution on SuperUser :

Chrome cookies folder in Windows 7:-

C:\Users\your_username\AppData\Local\Google\Chrome\User Data\Default\
You'll need a program like SQLite Database Browser to read it.

For Mac OS X, the file is located at :-
~/Library/Application Support/Google/Chrome/Default/Cookies

Set Session variable using javascript in PHP

The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:

$.post('/setsessionvariable.php', { name: 'value' });

You should, of course, be cautious about exposing such script.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

1.Set the following Environment Property on your active Shell. - open bash terminal and type in:

  $ export LD_BIND_NOW=1
  1. Re-Run the Jar or Java File

Note: for superuser in bash type su and press enter

Can't start Eclipse - Java was started but returned exit code=13

Adding vm argument to .ini file worked for me

-vm
C:\Program Files\Java\jdk1.7.0_65\bin\javaw.exe

Execute the setInterval function without delay the first time

I will suggest calling the functions in the following sequence

var _timer = setInterval(foo, delay, params);
foo(params)

You can also pass the _timer to the foo, if you want to clearInterval(_timer) on a certain condition

var _timer = setInterval(function() { foo(_timer, params) }, delay);
foo(_timer, params);

Take a char input from the Scanner

You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Exmple :

    import java.util.Scanner;

    public class InputC{


            public static void main(String[] args) {
                // TODO Auto-generated method stub
                   // Declare the object and initialize with
                   // predefined standard input object
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("Enter a character: ");
                    // Character input
                    char c = scanner.next().charAt(0);
                    // Print the read value
                    System.out.println("You have entered: "+c);
            }


        }

output

Enter a character: 
a
You have entered: a

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

Parsing JSON Array within JSON Object

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

Catching "Maximum request length exceeded"

You can solve this by increasing the maximum request length in your web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" />
    </system.web>
</configuration>

The example above is for a 100Mb limit.

RuntimeWarning: invalid value encountered in divide

Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.

How do I get the current date in Cocoa

You have problems with iOS 4.2? Use this Code:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);

-->20.01.2011 10:36:02

Sharing url link does not show thumbnail image on facebook

I ran into this and while I had the og:image (and others), I was missing og:url and og:type, so I added those and then it worked.

<meta property="og:url" content="<? 
 $url = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];; 
echo htmlentities($url,ENT_QUOTES); ?>"/> 

How can I compare two time strings in the format HH:MM:SS?

Try this code for the 24 hrs format of time.

<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");

var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();

if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>

Changing SVG image color with javascript

Sure, here is an example (standard HTML boilerplate omitted):

_x000D_
_x000D_
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">_x000D_
  <circle id="circle1" r="30" cx="34" cy="34" _x000D_
            style="fill: red; stroke: blue; stroke-width: 2"/>_x000D_
  </svg>_x000D_
<button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>
_x000D_
_x000D_
_x000D_

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Does Enter key trigger a click event?

Use (keyup.enter).

Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter pseudo-event.

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

Django datetime issues (default=datetime.now())

From the Python language reference, under Function definitions:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Fortunately, Django has a way to do what you want, if you use the auto_now argument for the DateTimeField:

date = models.DateTimeField(auto_now=True)

See the Django docs for DateTimeField.

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

What do "branch", "tag" and "trunk" mean in Subversion repositories?

They don't really have any formal meaning. A folder is a folder to SVN. They are a generally accepted way to organize your project.

  • The trunk is where you keep your main line of developmemt. The branch folder is where you might create, well, branches, which are hard to explain in a short post.

  • A branch is a copy of a subset of your project that you work on separately from the trunk. Maybe it's for experiments that might not go anywhere, or maybe it's for the next release, which you will later merge back into the trunk when it becomes stable.

  • And the tags folder is for creating tagged copies of your repository, usually at release checkpoints.

But like I said, to SVN, a folder is a folder. branch, trunk and tag are just a convention.

I'm using the word 'copy' liberally. SVN doesn't actually make full copies of things in the repository.

How to save the output of a console.log(object) to a file?

right click on console.. click save as.. its this simple.. you'll get an output text file

How do I remove a property from a JavaScript object?

@johnstock, we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object.

Above answers are appreciated.

_x000D_
_x000D_
var myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

// 1st and direct way 
delete myObject.regex; // delete myObject["regex"]
console.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }

// 2 way -  by using the concept of JavaScript's prototyping concept
Object.prototype.removeFromObjectByKey = function(key) {
  // If key exists, remove it and return true
  if (this[key] !== undefined) {
    delete this[key]
    return true;
  }
  // Else return false
  return false;
}

var isRemoved = myObject.removeFromObjectByKey('method')
console.log(myObject) // { ircEvent: 'PRIVMSG' }

// More examples
var obj = {
  a: 45,
  b: 56,
  c: 67
}
console.log(obj) // { a: 45, b: 56, c: 67 }

// Remove key 'a' from obj
isRemoved = obj.removeFromObjectByKey('a')
console.log(isRemoved); //true
console.log(obj); // { b: 56, c: 67 }

// Remove key 'd' from obj which doesn't exist
var isRemoved = obj.removeFromObjectByKey('d')
console.log(isRemoved); // false
console.log(obj); // { b: 56, c: 67 }
_x000D_
_x000D_
_x000D_

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

Change Row background color based on cell value DataTable

I used createdRow Function and solved my problem

    $('#result1').DataTable( {
        data: data['firstQuery'],
        columns: [
                        { title: 'Shipping Agent Code' },
                        { title: 'City' },
                        { title: 'Delivery Zone' },
                        { title: 'Total Slots Open ' },
                        { title: 'Slots Utilized' },
                        { title: 'Utilization %' },

                    ],
                    "columnDefs": [
                        {"className": "dt-center", "targets": "_all"}
                      ],
                      "createdRow": function( row, data, dataIndex){
                            if( data[5] >= 90  ){
                                $(row).css('background-color', '#F39B9B');
                            }
                            else if( data[5] <= 70  ){
                                $(row).css('background-color', '#A497E5');
                            }
                            else{
                                $(row).css('background-color', '#9EF395');
                            }

                        }
                } );

How to print the current time in a Batch-File?

This works with Windows 10, 8.x, 7, and possibly further back:

@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%

SQL Server query to find all permissions/access for all users in a database

I just added the following to Jeremy's answer because I had a role assigned to the database db_datareader which wasn't showing the permissions that role had. I tried going through all of the answers in everyone's posts but couldn't find anything that would do this so I added my own query.

    SELECT 
    UserType='Role', 
    DatabaseUserName = '{Role Members}',
    LoginName = DP2.name,
    Role = DP1.name,
    'SELECT' AS [PermissionType] ,
    [PermissionState]  = 'GRANT',
    [ObjectType] = 'Table',
    [Schema] = 'dbo',
    [ObjectName] = 'All Tables',
    [ColumnName] = NULL
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
AND DP2.name IS NOT NULL

how to change a selections options based on another select option selected?

You can use switch case like this:

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  $("#type").change(function () {_x000D_
     switch($(this).val()) {_x000D_
        case 'item1':_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
            break;_x000D_
        case 'item2':_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
            break;_x000D_
        case 'item3':_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
            break;_x000D_
        default:_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
     }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to combine two vectors into a data frame

You can use expand.grid( ) function.

x <-c(1,2,3)
y <-c(100,200,300)
expand.grid(cond=x,rating=y)

What is the correct wget command syntax for HTTPS with username and password?

I have found that wget does not properly authenticate with some servers, perhaps because it is only HTTP 1.0 compliant. In such cases, curl (which is HTTP 1.1 compliant) usually does the trick:

curl -o <filename-to-save-as> -u <username>:<password> <url>

React - How to pass HTML tags in props?

For me It worked by passing html tag in props children

<MyComponent>This is <strong>not</strong> working.</MyComponent>


var MyComponent = React.createClass({

   render: function() {
    return (
      <div>this.props.children</div>
    );
   },

How to declare variable and use it in the same Oracle SQL script?

Try using double quotes if it's a char variable:

DEFINE stupidvar = "'stupidvarcontent'";

or

DEFINE stupidvar = 'stupidvarcontent';

SELECT stupiddata  
FROM stupidtable  
WHERE stupidcolumn = '&stupidvar'

upd:

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = 'FL-208'

CODE
---------------
FL-208

SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = FL-208
select code from product where code = FL-208
                                      *
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined

RegEx match open tags except XHTML self-contained tags

Although it's not suitable and effective to use regular expressions for that purpose sometimes regular expressions provide quick solutions for simple match problems and in my view it's not that horrbile to use regular expressions for trivial works.

There is a definitive blog post about matching innermost HTML elements written by Steven Levithan.

How To Format A Block of Code Within a Presentation?

If you write your code in emacs then you might be interested in the htmlize elisp package.

Yarn: How to upgrade yarn version using terminal?

I updated yarn on my Ubuntu by running the following command from my terminal

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

source:https://yarnpkg.com/lang/en/docs/cli/self-update

Using "-Filter" with a variable

Or

-like '*'+$nameregex+'*'

if you would like to use wildcards.

How to find length of digits in an integer?

Assuming you are asking for the largest number you can store in an integer, the value is implementation dependent. I suggest that you don't think in that way when using python. In any case, quite a large value can be stored in a python 'integer'. Remember, Python uses duck typing!

Edit: I gave my answer before the clarification that the asker wanted the number of digits. For that, I agree with the method suggested by the accepted answer. Nothing more to add!

This app won't run unless you update Google Play Services (via Bazaar)

I spent about one day to configure the new gmaps API (Google Maps Android API v2) on the Android emulator. None of the methods of those I found on the Internet was working correctly for me. But still I did it. Here is how:

  1. Create a new emulator with the following configuration:

Enter image description here

On the other versions I could not configure because of various errors when I installed the necessary applications.

2) Start the emulator and install the following applications:

  • GoogleLoginService.apk
  • GoogleServicesFramework.apk
  • Phonesky.apk

You can do this with following commands:

2.1) adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
2.2) adb shell chmod 777 /system/app
2.3-2.5) adb push Each_of_the_3_apk_files.apk /system/app/

Links to download APK files. I have copied them from my rooted Android device.

3) Install Google Play Services and Google Maps on the emulator. I have an error 491, if I install them from Google Play store. I uploaded the apps to the emulator and run the installation locally. (You can use adb to install this). Links to the apps:

4) I successfully run a demo sample on the emulator after these steps. Here is a screenshot:

Google Maps

How to know which is running in Jupyter notebook?

from platform import python_version

print(python_version())

This will give you the exact version of python running your script. eg output:

3.6.5

Deactivate or remove the scrollbar on HTML

In HTML

<div style="overflow: hidden;">

in CSS

overflow: hidden;

you can also end scrolling for x or y separately

overflow-y: hidden; /* Hide vertical scrollbar */
  overflow-x: hidden; /* Hide horizontal scrollbar */

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Ubuntu 20.04:

Option 1 - set up a gem installation directory for your user account

For bash (for zsh, we would use .zshrc of course)

echo '# Install Ruby Gems to ~/gems' >> ~/.bashrc
echo 'export GEM_HOME="$HOME/gems"' >> ~/.bashrc
echo 'export PATH="$HOME/gems/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

Option 2 - use snap

Uninstall the apt-version (ruby-full) and reinstall it with snap

sudo apt-get remove ruby
sudo snap install ruby --classic

How to create a new figure in MATLAB?

While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.

Example: you have five figures on your desktop from a previous script you ran and you use

figure(1);
plot(...)

figure(2);
plot(...)

You just plotted over the figures on your desktop. However the code

figure;
plot(...)

figure;
plot(...)

just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

ElasticSearch: Unassigned Shards, how to fix?

For me, this was resolved by running this from the dev console: "POST /_cluster/reroute?retry_failed"

.....

I started by looking at the index list to see which indices were red and then ran

"get /_cat/shards?h=[INDEXNAME],shard,prirep,state,unassigned.reason"

and saw that it had shards stuck in ALLOCATION_FAILED state, so running the retry above caused them to re-try the allocation.

What is an example of the Liskov Substitution Principle?

An important example of the use of LSP is in software testing.

If I have a class A that is an LSP-compliant subclass of B, then I can reuse the test suite of B to test A.

To fully test subclass A, I probably need to add a few more test cases, but at the minimum I can reuse all of superclass B's test cases.

A way to realize is this by building what McGregor calls a "Parallel hierarchy for testing": My ATest class will inherit from BTest. Some form of injection is then needed to ensure the test case works with objects of type A rather than of type B (a simple template method pattern will do).

Note that reusing the super-test suite for all subclass implementations is in fact a way to test that these subclass implementations are LSP-compliant. Thus, one can also argue that one should run the superclass test suite in the context of any subclass.

See also the answer to the Stackoverflow question "Can I implement a series of reusable tests to test an interface's implementation?"

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

The below programme will help you drop duplicates on whole , or if you want to drop duplicates based on certain columns , you can even do that:

import org.apache.spark.sql.SparkSession

object DropDuplicates {
def main(args: Array[String]) {
val spark =
  SparkSession.builder()
    .appName("DataFrame-DropDuplicates")
    .master("local[4]")
    .getOrCreate()

import spark.implicits._

// create an RDD of tuples with some data
val custs = Seq(
  (1, "Widget Co", 120000.00, 0.00, "AZ"),
  (2, "Acme Widgets", 410500.00, 500.00, "CA"),
  (3, "Widgetry", 410500.00, 200.00, "CA"),
  (4, "Widgets R Us", 410500.00, 0.0, "CA"),
  (3, "Widgetry", 410500.00, 200.00, "CA"),
  (5, "Ye Olde Widgete", 500.00, 0.0, "MA"),
  (6, "Widget Co", 12000.00, 10.00, "AZ")
)
val customerRows = spark.sparkContext.parallelize(custs, 4)

// convert RDD of tuples to DataFrame by supplying column names
val customerDF = customerRows.toDF("id", "name", "sales", "discount", "state")

println("*** Here's the whole DataFrame with duplicates")

customerDF.printSchema()

customerDF.show()

// drop fully identical rows
val withoutDuplicates = customerDF.dropDuplicates()

println("*** Now without duplicates")

withoutDuplicates.show()

// drop fully identical rows
val withoutPartials = customerDF.dropDuplicates(Seq("name", "state"))

println("*** Now without partial duplicates too")

withoutPartials.show()

 }
 }

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Row count with PDO

<table>
      <thead>
           <tr>
                <th>Sn.</th>
                <th>Name</th>
           </tr>
      </thead>
      <tbody>
<?php
     $i=0;
     $statement = $db->prepare("SELECT * FROM tbl_user ORDER BY name ASC");
     $statement->execute();
     $result = $statement->fetchColumn();
     foreach($result as $row) {
        $i++;
    ?>  
      <tr>
         <td><?php echo $i; ?></td>
         <td><?php echo $row['name']; ?></td>
      </tr>
     <?php
          }
     ?>
     </tbody>
</table>

ValueError: could not convert string to float: id

Obviously some of your lines don't have valid float data, specifically some line have text id which can't be converted to float.

When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.

#!/usr/bin/python

import os,sys
from scipy import stats
import numpy as np

f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
        list1=[float(x) for x in l1]
        list2=[float(x) for x in l2]
    except ValueError,e:
        print "error",e,"on line",i
    result=stats.ttest_ind(list1,list2)
    print result[1]

Clearing input in vuejs form

These solutions are good but if you want to go for less work then you can use $refs

<form ref="anyName" @submit="submitForm">
</form>

<script>
   methods: {
      submitForm(){
         // Your form submission
         this.$refs.anyName.reset(); // This will clear that form
      }
   }
</script>

What's a clean way to stop mongod on Mac OS X?

The solutions provided by others used to work for me but is not working for me anymore, which is as below.

brew services stop mongodb
brew services start mongodb

brew services list gives

Name              Status  User      Plist
mongodb-community started XXXXXXXXX /Users/XXXXXXXXX/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

So I used mongodb-community instead of mongodb which worked for me

brew services stop mongodb-community
brew services start mongodb-community

HttpClient.GetAsync(...) never returns when using await/async

I was using to many await, so i was not getting response , i converted in to sync call its started working

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Method = HttpMethod.Get;
                request.RequestUri = new Uri(URL);
                var response = client.GetAsync(URL).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
               

Adding calculated column(s) to a dataframe in pandas

The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map and apply functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.

>>> d
    A   B  C
0  11  13  5
1   6   7  4
2   8   3  6
3   4   8  7
4   0   1  7
>>> (d.A + d.B) / d.C
0    4.800000
1    3.250000
2    1.833333
3    1.714286
4    0.142857
>>> d.A > d.C
0     True
1     True
2     True
3    False
4    False

If you need to use operations like max and min within a row, you can use apply with axis=1 to apply any function you like to each row. Here's an example that computes min(A, B)-C, which seems to be like your "lower wick":

>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0    6
1    2
2   -3
3   -3
4   -7

Hopefully that gives you some idea of how to proceed.

Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:

d['A'][:-1] < d['C'][1:]

and this does it the other way, telling you which rows have A less than the preceding row's C:

d['A'][1:] < d['C'][:-1]

Doing ['A"][:-1] slices off the last element of column A, and doing ['C'][1:] slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.

Where's my JSON data in my incoming Django request?

Something like this. It's worked: Request data from client

registerData = {
{% for field in userFields%}
  {{ field.name }}: {{ field.name }},
{% endfor %}
}


var request = $.ajax({
   url: "{% url 'MainApp:rq-create-account-json' %}",
   method: "POST",
   async: false,
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify(registerData),
   dataType: "json"
});

request.done(function (msg) {
   [alert(msg);]
   alert(msg.name);
});

request.fail(function (jqXHR, status) {
  alert(status);
});

Process request at the server

@csrf_exempt
def rq_create_account_json(request):
   if request.is_ajax():
       if request.method == 'POST':
           json_data = json.loads(request.body)
           print(json_data)
           return JsonResponse(json_data)
   return HttpResponse("Error")

Global npm install location on windows?

If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module

$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s

How to convert a Java String to an ASCII byte array?

There is only one character wrong in the code you tried:

Charset characterSet = Charset.forName("US-ASCII");
String string = "Wazzup";
byte[] bytes = String.getBytes(characterSet);
               ^

Notice the upper case "String". This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:

byte[] bytes = string.getBytes(characterSet);

How to load an ImageView by URL in Android?

I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev). You get the Input stream of the image (from web)

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.

InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");

Interface type check with Typescript

How about User-Defined Type Guards? https://www.typescriptlang.org/docs/handbook/advanced-types.html

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function isFish(pet: Fish | Bird): pet is Fish { //magic happens here
    return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}

How to get char from string by index?

First make sure the required number is a valid index for the string from beginning or end , then you can simply use array subscript notation. use len(s) to get string length

>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> 

How can I execute a python script from an html button?

Using a UI Framework would be a lot cleaner (and involve fewer components). Here is an example using wxPython:

import wx
import os
class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Launch Scripts")
        panel = wx.Panel(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        buttonA = wx.Button(panel, id=wx.ID_ANY, label="App A", name="MYSCRIPT")
        buttonB = wx.Button(panel, id=wx.ID_ANY, label="App B", name="MYOtherSCRIPT")
        buttonC = wx.Button(panel, id=wx.ID_ANY, label="App C", name="SomeDifferentScript")
        buttons = [buttonA, buttonB, buttonC]

        for button in buttons:
            self.buildButtons(button, sizer)

        panel.SetSizer(sizer)

    def buildButtons(self, btn, sizer):
        btn.Bind(wx.EVT_BUTTON, self.onButton)
        sizer.Add(btn, 0, wx.ALL, 5)

    def onButton(self, event):
        """
        This method is fired when its corresponding button is pressed, taking the script from it's name
        """
        button = event.GetEventObject()

        os.system('python {}.py'.format(button.GetName()))

        button_id = event.GetId()
        button_by_id = self.FindWindowById(button_id)
        print "The button you pressed was labeled: " + button_by_id.GetLabel()
        print "The button's name is " + button_by_id.GetName()

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

I haven't tested this yet, and I'm sure there are cleaner ways of launching a python script form a python script, but the idea I think will still hold. Good luck!

Is there a free GUI management tool for Oracle Database Express?

There are a few options:

  • Database.net is a windows GUI to connect to many different types of databases, oracle included.
  • Oracle SQL Developer is a free tool from Oracle.
  • SQuirreL SQL is a java based client that can connect to any database that uses JDBC drivers.

I'm sure there are others out there that you could use too...

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

please note, if you use $filter like this:

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

and you happened to have another grade for, Oh I don't know, CC or AC or C+ or CCC it pulls them in to. you need to append a requirement for an exact match:

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);

This really killed me when I was pulling in some commission details like this:

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];

only get called in for a bug because it was pulling in the commission ID 56 rather than 6.

Adding the true forces an exact match.

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];

Yet still, I prefer this (I use typescript, hence the "Let" and =>):

let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{ 
             return item.commission_type_id === 6;
           })[0];

I do that because, at some point down the road, I might want to get some more info from that filtered data, etc... having the function right in there kind of leaves the hood open.

Changing text color onclick

   <p id="text" onclick="func()">
    Click on text to change
</p>
<script>
function func()
{
    document.getElementById("text").style.color="red";
    document.getElementById("text").style.font="calibri";
}
</script>

Making an iframe responsive

I noticed that leowebdev's post did seem to work on my end, however, it did knock out two elements of the site that I am trying to make: the scrolling and the footer.

The scrolling I got back by adding a scrolling="yes" To the iframe embed code.

I am not sure if the footer is automatically knocked out because of the responsiveness or not, but hopefully someone else knows that answer.

Edit a commit message in SourceTree Windows (already pushed to remote)

Update

Note: this answer was originally written with regard to older versions of SourceTree for Windows, and is now out-of-date.

See my new answer for the current version of SourceTree for Windows, 1.5.2.0. I'm leaving this answer behind for historical purposes.

Original Answer

as I'm on Windows I don't have a command line tool nor do I know how to use one :( Is it the only way to get that sorted out? The GUI doesn't cover all the git's functions? — Original Poster

Regarding Git GUIs, no, they don't cover all of Git's functions. They don't even come close. I suggest you check out one of the answers in How do I edit an incorrect commit message in Git?, Git is flexible enough that there are multiple solutions...from the command line.

SourceTree might actually come with the msysgit bash shell already, or it might be able to use the standard Windows command shell. Either way, you open it up form SourceTree by clicking the Terminal button:

enter image description here

You set which terminal SourceTree uses (bash or Windows) here:

enter image description here

One way to solve the problem in SourceTree

That being said, here's one way you can do it in SourceTree. Since you mentioned in the comments that you don't mind "reverting back to the faulty commit" (by which I assume you actually mean resetting, which is a different operation in Git), then here are the steps:

  1. Do a hard reset in SourceTree to the bad commit by right-clicking on it and selecting Reset current branch to this commit, and selecting the hard reset option from the drop down. enter image description here
  2. Click the Commit button, then
  3. Click on the checkbox at the bottom that says "Amend latest commit". enter image description here
  4. Make the changes you want to the message, then click Commit again. Voila!

Regarding this comment:

if it's not possible because it's already pushed to Bitbucket, I would not mind creating a new repository and starting over.

Does this mean that you're the only person working on the repo? This is important because it's not trivial to change the history of a repo (like by amending a commit) without causing problems for your collaborators. However, assuming that you're the only person working on the repo, then the next thing you would want to do is force push your changed history to the remote.

Be aware, though, that because you did a hard reset to the faulty commit, then force pushing causes you to lose all work that come after it previously. If that's okay, then you might need to use the following command at the command line to do the force push, because I couldn't find an option to do it in SourceTree:

git push remote-repo head -f

This also assumes that BitBucket will allow you to force push to a repo.

You should really learn how to use Git from the command line anyways though, it'll make you more proficient in Git. #ProTip, use msysgit and turn on Quick Edit mode on in the terminal properties, so that you can double click to highlight a line of text, right click to copy, and right click again to paste. It's pretty quick.

Convert DataSet to List

 List<GSTEntity.gst_jobwork_to_mfgmaster> ListToGetJwToMfData = new List<GSTEntity.gst_jobwork_to_mfgmaster>();
            DataSet getJwtMF = new DataSet();
            getJwtMF = objgst_jobwork_to_mfgmaster_BLL.GetDataJobWorkToMfg(AssesseeId, PremiseId,  Fyear,  MonthId, out webex);
            if(getJwtMF.Tables["gst_jobwork_to_mfgmaster"] != null)
            {

                ListToGetJwToMfData = (from master in getJwtMF.Tables["gst_jobwork_to_mfgmaster"].AsEnumerable() select new GSTEntity.gst_jobwork_to_mfgmaster { Partygstin = master.Field<string>("Partygstin"), Partystate =
                                       master.Field<string>("Partystate"), NatureOfTransaction = master.Field<string>("NatureOfTransaction"), ChallanNo = master.Field<string>("ChallanNo"), ChallanDate=master.Field<int>("ChallanDate"),  OtherJW_ChallanNo=master.Field<string>("OtherJW_ChallanNo"),   OtherJW_ChallanDate = master.Field<int>("OtherJW_ChallanDate"),
                    OtherJW_GSTIN=master.Field<string>("OtherJW_GSTIN"),
                    OtherJW_State = master.Field<string>("OtherJW_State"),
                    InvoiceNo = master.Field<string>("InvoiceNo"),
                    InvoiceDate=master.Field<int>("InvoiceDate"),
                    Description =master.Field<string>("Description"),
                    UQC= master.Field<string>("UQC"),
                    qty=master.Field<decimal>("qty"),
                    TaxValue=master.Field<decimal>("TaxValue"),
                    Id=master.Field<int>("Id")                        

                }).ToList();

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals

How to remove docker completely from ubuntu 14.04

Apparently, the system I was using had the docker-ce not Docker. Thus, running below command did the trick.

sudo apt-get purge docker-ce

sudo rm -rf /var/lib/docker

hope it helps

Using NULL in C++?

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

How to keep a git branch in sync with master

concept47's approach is the right way to do it, but I'd advise to merge with the --no-ff option in order to keep your commit history clear.

git checkout develop
git pull --rebase
git checkout NewFeatureBranch
git merge --no-ff master

html text input onchange event

onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:

<input
   type       = "text" 
   onchange   = "myHandler();"
   onkeypress = "this.onchange();"
   onpaste    = "this.onchange();"
   oninput    = "this.onchange();"
/>

Excel function to get first word from sentence in other cell

Generic solution extracting the first "n" words of refcell string into a new string of "x" number of characters

=LEFT(SUBSTITUTE(***refcell***&" "," ",REPT(" ",***x***),***n***),***x***)

Assuming A1 has text string to extract, the 1st word extracted to a 15 character result

=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",15),1),15)

This would result in "Toronto" being returned to a 15 character string. 1st 2 words extracted to a 30 character result

=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",30),2),30)

would result in "Toronto is" being returned to a 30 character string

How to include a PHP variable inside a MySQL statement

The best option is prepared statements. Messing around with quotes and escapes is harder work to begin with, and difficult to maintain. Sooner or later you will end up accidentally forgetting to quote something or end up escaping the same string twice, or mess up something like that. Might be years before you find those type of bugs.

http://php.net/manual/en/pdo.prepared-statements.php

How to update/modify an XML file in python?

What you really want to do is use an XML parser and append the new elements with the API provided.

Then simply overwrite the file.

The easiest to use would probably be a DOM parser like the one below:

http://docs.python.org/library/xml.dom.minidom.html

Stuck at ".android/repositories.cfg could not be loaded."

Actually, after waiting some time it eventually goes beyond that step. Even with --verbose, you won't have any information that it computes anything, but it does.

Patience is the key :)

PS : For anyone that cancelled at that step, if you try to reinstall the android-sdk package, it will complain that Error: No such file or directory - /usr/local/share/android-sdk. You can just touch /usr/local/share/android-sdk to get rid of that error and go on with the reinstall.

How to Use Order By for Multiple Columns in Laravel 4?

Use order by like this:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();

Java constant examples (Create a java file having only constants)

You can also use the Properties class

Here's the constants file called

# this will hold all of the constants
frameWidth = 1600
frameHeight = 900

Here is the code that uses the constants

public class SimpleGuiAnimation {

    int frameWidth;
    int frameHeight;


    public SimpleGuiAnimation() {
        Properties properties = new Properties();

        try {
            File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
            FileInputStream fileInputStream = new FileInputStream(file);
            properties.load(fileInputStream);
        }
        catch (FileNotFoundException fileNotFoundException) {
            System.out.println("Could not find the properties file" + fileNotFoundException);
        }
        catch (Exception exception) {
            System.out.println("Could not load properties file" + exception.toString());
        }


        this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
        this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
    }

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Depending on your platform you can use: sqlite3 file_name.db from the terminal. .tables will list the tables, .schema is full layout. SQLite commands like: select * from table_name; and such will print out the full contents. Type: ".exit" to exit. No need to download a GUI application.Use a semi-colon if you want it to execute a single command. Decent SQLite usage tutorial http://www.thegeekstuff.com/2012/09/sqlite-command-examples/

git pull from master into the development branch

git pull origin master --allow-unrelated-histories

You might want to use this if your histories doesnt match and want to merge it anyway..

refer here

What is the best way to generate a unique and short file name in Java

Problem is synchronization. Separate out regions of conflict.

Name the file as : (server-name)_(thread/process-name)_(millisecond/timestamp).(extension)
example : aws1_t1_1447402821007.png

Is there an equivalent method to C's scanf in Java?

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.

Following code is taken from cited website:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

Regards.

What is Linux’s native GUI API?

Wayland is also worth mentioning as it is mostly referred as a "future X11 killer".

Also note that Android and some other mobile operating systems don't include X11 although they have a Linux kernel, so in that sense X11 is not native to all Linux systems.

Being cross-platform has nothing to do with being native. Cocoa has also been ported to other platforms via GNUStep but it is still native to OS X / macOS.

Left function in c#

var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
    // Do your stuff.
}

Trying to handle "back" navigation button action in iOS

Try this code using VIewWillDisappear method to detect the press of The back button of NavigationItem:

-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) 
    {
        // Navigation button was pressed. Do some stuff 
        [self.navigationController popViewControllerAnimated:NO];
    }
    [super viewWillDisappear:animated];
}

OR There is another way to get Action of the Navigation BAck button.

Create Custom button for UINavigationItem of back button .

For Ex:

In ViewDidLoad :

- (void)viewDidLoad 
{
    [super viewDidLoad];
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
    self.navigationItem.leftBarButtonItem=newBackButton;
}

-(void)home:(UIBarButtonItem *)sender 
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

Swift :

override func willMoveToParentViewController(parent: UIViewController?) 
{
    if parent == nil 
    {
        // Back btn Event handler
    }
}

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

HTML Submit-button: Different value / button-text?

It's possible using the button element.

<button name="name" value="value" type="submit">Sök</button>

From the W3C page on button:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.

Make scrollbars only visible when a Div is hovered over?

_x000D_
_x000D_
div {_x000D_
  height: 100px;_x000D_
  width: 50%;_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It_x000D_
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop_x000D_
    publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Would something like that work?

Two color borders

Another way is to use box-shadow:

#mybox {
box-shadow:
  0 0 0 1px #CCC,
  0 0 0 2px #888,
  0 0 0 3px #444,
  0 0 0 4px #000;
-moz-box-shadow:
  0 0 0 1px #CCC,
  0 0 0 2px #888,
  0 0 0 3px #444,
  0 0 0 4px #000;
-webkit-shadow:
  0 0 0 1px #CCC,
  0 0 0 2px #888,
  0 0 0 3px #444,
  0 0 0 4px #000;
}

<div id="mybox">ABC</div>

See example here.

how to add css class to html generic control div?

dynDiv.Attributes["class"] = "myCssClass";

mysql select from n last rows

Might be a very late answer, but this is good and simple.

select * from table_name order by id desc limit 5

This query will return a set of last 5 values(last 5 rows) you 've inserted in your table

How to retry after exception?

for _ in range(5):
    try:
        # replace this with something that may fail
        raise ValueError("foo")

    # replace Exception with a more specific exception
    except Exception as e:
        err = e
        continue

    # no exception, continue remainder of code
    else:
        break

# did not break the for loop, therefore all attempts
# raised an exception
else:
    raise err

My version is similar to several of the above, but doesn't use a separate while loop, and re-raises the latest exception if all retries fail. Could explicitly set err = None at the top, but not strictly necessary as it should only execute the final else block if there was an error and therefore err is set.

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

In SQL Server 2016 (or newer) you can use this:

CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...

In older versions of SQL server you have to use something like

DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';

IF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN EXEC('CREATE ' + @script) END
ELSE
BEGIN EXEC('ALTER ' + @script) END

Or, if there are no dependencies on the view, you can just drop it and recreate:

IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN 
   DROP VIEW [VW_NAMEOFVIEW];
END

CREATE VIEW [VW_NAMEOFVIEW] AS ...

Spring Data JPA map the native query result to Non-Entity POJO

Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult?

@SqlResultSetMapping(
    name="groupDetailsMapping",
    classes={
        @ConstructorResult(
            targetClass=GroupDetails.class,
            columns={
                @ColumnResult(name="GROUP_ID"),
                @ColumnResult(name="USER_ID")
            }
        )
    }
)

@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")

and use following in repository interface:

GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);

According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using @NamedNativeQuery, @SqlResultSetMapping and @ConstructorResult you should be able to achieve that behaviour

How to click a browser button with JavaScript automatically?

You can use

setInterval(function(){ 
    document.getElementById("yourbutton").click();
}, 1000);

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.

For example:

import math
import numpy as np
alpha = 0.2 
beta=1-alpha
C = (-math.log(1-beta))/alpha

coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C

The error:

    coff *= C 
TypeError: can't multiply sequence by non-int of type 'float'

The solution - convert the list to numpy array:

coff = np.asarray(coff) * C

Should I write script in the body or the head of the html?

I would answer this with multiple options actually, the some of which actually render in the body.

  • Place library script such as the jQuery library in the head section.
  • Place normal script in the head unless it becomes a performance/page load issue.
  • Place script associated with includes, within and at the end of that include. One example of this is .ascx user controls in asp.net pages - place the script at the end of that markup.
  • Place script that impacts the render of the page at the end of the body (before the body closure).
  • do NOT place script in the markup such as <input onclick="myfunction()"/> - better to put it in event handlers in your script body instead.
  • If you cannot decide, put it in the head until you have a reason not to such as page blocking issues.

Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).

EDIT: references:

Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; } on the div)

Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html

EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.

How to change mysql to mysqli?

similar to dhw's answer but you don't have to worry about setting the link as global in all the function because that is kind of difficult:

just use this code in your config file:

$sv_connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$db_connection = mysqli_select_db ($sv_connection, $dbname);
mysqli_set_charset($sv_connection, 'utf8'); //optional

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}


function mysqljx_query($q){
    global $sv_connection;
    return mysqli_query($sv_connection, $q);
}

function mysqljx_fetch_array($r){
    return mysqli_fetch_array($r);
}

function mysqljx_fetch_assoc($r){
    return mysqli_fetch_assoc($r);
}

function mysqljx_num_rows($r){
    return mysqli_num_rows($r);
}

function mysqljx_insert_id(){
    global $sv_connection;
    return mysqli_insert_id($sv_connection);
}

function mysqljx_real_escape_string($string){
    global $sv_connection;
    return mysqli_real_escape_string($sv_connection, $string);
}

-now do a search for php files that contain "mysql_" (i used total commander for that - Alt+F7, search for "*.php", find text "mysql_", Start search, Feed to listbox)

-drag&drop them all in Notepad++, there u press CTRL+H, Find what: "mysql_", Replace with "mysqljx_", "Replace All in All Opened Documents"

if you are worried that you have other functions than the ones listed above just replace one by one ("mysql_query" with "mysqljx_query", then mysql_fetch_array with "mysqljx_fetch_array" etc..) and then search again for "mysql_" and if its still there its a uncovered function and you can just add it same as the rest..

that is it

how to hide keyboard after typing in EditText in android?

I use this method to remove keyboard from edit text:

 public static void hideKeyboard(Activity activity, IBinder binder) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (binder != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(binder, 0);//HIDE_NOT_ALWAYS
            inputManager.showSoftInputFromInputMethod(binder, 0);
        }
    }
}

And this method to remove keyboard from activity (not work in some cases - for example, when edittext, to wich is binded keyboard, lost focus, it won't work. But for other situations, it works great, and you do not have to care about element that holds the keyboard).

 public static void hideKeyboard(Activity activity) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            inputManager.showSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}

Inner Joining three tables

dbo.tableA AS A INNER JOIN dbo.TableB AS B
ON A.common = B.common INNER JOIN TableC C
ON B.common = C.common