Programs & Examples On #Multiple resultsets

C# Iterate through Class properties

// the index of each item in fieldNames must correspond to 
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};

for (int e = 0; e < fieldNames.Length - 1; e++)
{
    newRecord
       .GetType()
       .GetProperty(fieldNames[e])
       .SetValue(newRecord, resultItems[e]);
}

how to implement Pagination in reactJs

I have tried to recreate the simple pagination example given by piotr-berebecki which was great. But when there will be a lot of pages then the pagination will overflow in the screen. So, I used previous and back button along with forward and backward button to stream back and forth between the pages. And for design part I have used bootstrap 3.

You can customize no of pages to display in pagination using the pagebound values. Make sure to use same value for upperPageBound and pageBound.

    class TodoApp extends React.Component {
          constructor() {
            super();
            this.state = {
              todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'],
              currentPage: 1,
              todosPerPage: 3,
              upperPageBound: 3,
              lowerPageBound: 0,
              isPrevBtnActive: 'disabled',
              isNextBtnActive: '',
              pageBound: 3
            };
            this.handleClick = this.handleClick.bind(this);
            this.btnDecrementClick = this.btnDecrementClick.bind(this);
            this.btnIncrementClick = this.btnIncrementClick.bind(this);
            this.btnNextClick = this.btnNextClick.bind(this);
            this.btnPrevClick = this.btnPrevClick.bind(this);
            // this.componentDidMount = this.componentDidMount.bind(this);
            this.setPrevAndNextBtnClass = this.setPrevAndNextBtnClass.bind(this);
          }
          componentDidUpdate() {
                $("ul li.active").removeClass('active');
                $('ul li#'+this.state.currentPage).addClass('active');
          }
          handleClick(event) {
            let listid = Number(event.target.id);
            this.setState({
              currentPage: listid
            });
            $("ul li.active").removeClass('active');
            $('ul li#'+listid).addClass('active');
            this.setPrevAndNextBtnClass(listid);
          }
          setPrevAndNextBtnClass(listid) {
            let totalPage = Math.ceil(this.state.todos.length / this.state.todosPerPage);
            this.setState({isNextBtnActive: 'disabled'});
            this.setState({isPrevBtnActive: 'disabled'});
            if(totalPage === listid && totalPage > 1){
                this.setState({isPrevBtnActive: ''});
            }
            else if(listid === 1 && totalPage > 1){
                this.setState({isNextBtnActive: ''});
            }
            else if(totalPage > 1){
                this.setState({isNextBtnActive: ''});
                this.setState({isPrevBtnActive: ''});
            }
        }
          btnIncrementClick() {
              this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
              this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
              let listid = this.state.upperPageBound + 1;
              this.setState({ currentPage: listid});
              this.setPrevAndNextBtnClass(listid);
        }
          btnDecrementClick() {
            this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
            this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            let listid = this.state.upperPageBound - this.state.pageBound;
            this.setState({ currentPage: listid});
            this.setPrevAndNextBtnClass(listid);
        }
        btnPrevClick() {
            if((this.state.currentPage -1)%this.state.pageBound === 0 ){
                this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            }
            let listid = this.state.currentPage - 1;
            this.setState({ currentPage : listid});
            this.setPrevAndNextBtnClass(listid);
        }
        btnNextClick() {
            if((this.state.currentPage +1) > this.state.upperPageBound ){
                this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
            }
            let listid = this.state.currentPage + 1;
            this.setState({ currentPage : listid});
            this.setPrevAndNextBtnClass(listid);
        }
          render() {
            const { todos, currentPage, todosPerPage,upperPageBound,lowerPageBound,isPrevBtnActive,isNextBtnActive } = this.state;
            // Logic for displaying current todos
            const indexOfLastTodo = currentPage * todosPerPage;
            const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
            const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

            const renderTodos = currentTodos.map((todo, index) => {
              return <li key={index}>{todo}</li>;
            });

            // Logic for displaying page numbers
            const pageNumbers = [];
            for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
              pageNumbers.push(i);
            }

            const renderPageNumbers = pageNumbers.map(number => {
                if(number === 1 && currentPage === 1){
                    return(
                        <li key={number} className='active' id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                    )
                }
                else if((number < upperPageBound + 1) && number > lowerPageBound){
                    return(
                        <li key={number} id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                    )
                }
            });
            let pageIncrementBtn = null;
            if(pageNumbers.length > upperPageBound){
                pageIncrementBtn = <li className=''><a href='#' onClick={this.btnIncrementClick}> &hellip; </a></li>
            }
            let pageDecrementBtn = null;
            if(lowerPageBound >= 1){
                pageDecrementBtn = <li className=''><a href='#' onClick={this.btnDecrementClick}> &hellip; </a></li>
            }
            let renderPrevBtn = null;
            if(isPrevBtnActive === 'disabled') {
                renderPrevBtn = <li className={isPrevBtnActive}><span id="btnPrev"> Prev </span></li>
            }
            else{
                renderPrevBtn = <li className={isPrevBtnActive}><a href='#' id="btnPrev" onClick={this.btnPrevClick}> Prev </a></li>
            }
            let renderNextBtn = null;
            if(isNextBtnActive === 'disabled') {
                renderNextBtn = <li className={isNextBtnActive}><span id="btnNext"> Next </span></li>
            }
            else{
                renderNextBtn = <li className={isNextBtnActive}><a href='#' id="btnNext" onClick={this.btnNextClick}> Next </a></li>
            }
            return (
              <div>
                  <ul>
                  {renderTodos}
                </ul>
                <ul id="page-numbers" className="pagination">
                  {renderPrevBtn}
                  {pageDecrementBtn}
                  {renderPageNumbers}
                  {pageIncrementBtn}
                  {renderNextBtn}
                </ul>
              </div>
            );
          }
        }


        ReactDOM.render(
          <TodoApp />,
          document.getElementById('app')
        );

Working demo link : https://codepen.io/mhmanandhar/pen/oEWBqx

Image : simple react pagination

Update all objects in a collection using LINQ

I actually found an extension method that will do what I want nicely

public static IEnumerable<T> ForEach<T>(
    this IEnumerable<T> source,
    Action<T> act)
{
    foreach (T element in source) act(element);
    return source;
}

How to get Month Name from Calendar?

This works for me:

String getMonthName(int monthNumber) {
    String[] months = new DateFormatSymbols().getMonths();
    int n = monthNumber-1;
    return (n >= 0 && n <= 11) ? months[n] : "wrong number";
}

To returns "September" with one line:

String month = getMonthName(9);

SQL error "ORA-01722: invalid number"

The ORA-01722 error is pretty straightforward. According to Tom Kyte:

We've attempted to either explicity or implicity convert a character string to a number and it is failing.

However, where the problem is is often not apparent at first. This page helped me to troubleshoot, find, and fix my problem. Hint: look for places where you are explicitly or implicitly converting a string to a number. (I had NVL(number_field, 'string') in my code.)

What HTTP traffic monitor would you recommend for Windows?

I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.

Which icon sizes should my Windows application's icon include?

The Microsoft UX icon guideline says:

"Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256)."

To me this implies (but does not explicitly state, unfortunately) that you should supply those 4 sizes.

Additional details regarding color formats, which you may also find useful:

  • "Icon files require 8-bit and 4-bit palette versions as well, to support the default setting in a remote desktop."

  • "Only a 32-bit copy of the 256x256 pixel image should be included, and only the 256x256 pixel image should be compressed [as PNG] to keep the file size down."

Shrinking navigation bar when scrolling down (bootstrap3)

Sticky navbar:

To make a sticky nav you need to add the class navbar-fixed-top to your nav

Official documentation:
http://getbootstrap.com/components/#navbar-fixed-top

Official example:
http://getbootstrap.com/examples/navbar-fixed-top/

A simple example code:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container">
    ...
  </div>
</nav>

with related jsfiddle: http://jsfiddle.net/ur7t8/

Resize the navbar:

If you want the nav bar to resize while you scroll the page you can give a look to this example: http://www.bootply.com/109943

JS

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

CSS

nav.navbar.shrink {
  min-height: 35px;
}

Animation:

To add an animation while you scroll, all you need to do is set a transition on the nav

CSS

nav.navbar{
  background-color:#ccc;
   // Animation
   -webkit-transition: all 0.4s ease;
   transition: all 0.4s ease;
}

I made a jsfiddle with the full example code: http://jsfiddle.net/Filo/m7yww8oa/

Pass connection string to code-first DbContext

Check the syntax of your connection string in the web.config. It should be something like ConnectionString="Data Source=C:\DataDictionary\NerdDinner.sdf"

Mean of a column in a data frame, given the column's name

Suppose you have a data frame(say df) with columns "x" and "y", you can find mean of column (x or y) using:

1.Using mean() function

z<-mean(df$x)

2.Using the column name(say x) as a variable using attach() function

 attach(df)
 mean(x)

When done you can call detach() to remove "x"

detach()

3.Using with() function, it lets you use columns of data frame as distinct variables.

 z<-with(df,mean(x))

What is the difference between a .cpp file and a .h file?

.h files, or header files, are used to list the publicly accessible instance variables and and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.

The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.

How to enable LogCat/Console in Eclipse for Android?

In the "Window" menu, open "Open Perspective" -> "Debug".

alt text click On the plus image icon(you see the below image at status bar), and then select "Logcat"....

Android ListView with different layouts for each row

Since you know how many types of layout you would have - it's possible to use those methods.

getViewTypeCount() - this methods returns information how many types of rows do you have in your list

getItemViewType(int position) - returns information which layout type you should use based on position

Then you inflate layout only if it's null and determine type using getItemViewType.

Look at this tutorial for further information.

To achieve some optimizations in structure that you've described in comment I would suggest:

  • Storing views in object called ViewHolder. It would increase speed because you won't have to call findViewById() every time in getView method. See List14 in API demos.
  • Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.

I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.

Delete item from state array in react

It's Very Simple First You Define a value

state = {
  checked_Array: []
}

Now,

fun(index) {
  var checked = this.state.checked_Array;
  var values = checked.indexOf(index)
  checked.splice(values, 1);
  this.setState({checked_Array: checked});
  console.log(this.state.checked_Array)
}

Illegal string offset Warning PHP

There are a lot of great answers here - but I found my issue was quite a bit more simple.

I was trying to run the following command:

$x['name']   = $j['name'];

and I was getting this illegal string error on $x['name'] because I hadn't defined the array first. So I put the following line of code in before trying to assign things to $x[]:

$x = array();

and it worked.

Turning Sonar off for certain code

You can annotate a class or a method with SuppressWarnings

@java.lang.SuppressWarnings("squid:S00112")

squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.

How to detect a route change in Angular?

Router 3.0.0-beta.2 should be

this.router.events.subscribe(path => {
  console.log('path = ', path);
});

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

For resovle this issue:

  1. Go to Xcode/Preferences/Accounts
  2. Click on your apple id account;
  3. Click - "View Details" (is open a new window with "signing identities" and "provisioning profiles";
  4. Delete all certificates from "Provisioning profiles", empty trash;
  5. Delete your Apple-ID account;
  6. Log in again with your apple id and build app!

Good luck!

Is it possible to use "return" in stored procedure?

CREATE PROCEDURE pr_emp(dept_id IN NUMBER,vv_ename out varchar2  )
 AS
 v_ename emp%rowtype;
CURSOR c_emp IS
    SELECT ename
    FROM emp where deptno=dept_id;
 BEGIN
     OPEN c;
     loop
        FETCH c_emp INTO v_ename;
        return v_ename; 
        vv_ename := v_ename 
        exit when c_emp%notfound;
     end loop;
     CLOSE c_emp;


 END pr_emp;

Full Screen Theme for AppCompat

When you use Theme.AppCompat in your application you can use FullScreenTheme by adding the code below to styles.

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

and also mention in your manifest file.

<activity
   android:name=".activities.FullViewActivity"
   android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen" 
/>

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

I think it's a version problem, you just have to uninstall the old version of composer, then do a new installation of its new version.

 apt remove composer

and follow the steps:

  1. download the composer from its official release site by making use of the following command.
 wget https://getcomposer.org/download/1.6.3/composer.phar
  1. Before you proceed with the installation, you should rename before you install and make it an executable file.
  mv composer.phar composer
  chmod +x composer
  1. Now install the package by making use the following command.
 ./composer
  1. The composer has been successfully installed now, make it access globally using the following command. for Ubuntu 16
 mv composer /usr/bin/

for Ubuntu 18

 mv composer /usr/local/bin/

Get JavaScript object from array of objects by value of property

Filter array of objects, which property matches value, returns array:

var result = jsObjects.filter(obj => {
  return obj.b === 6
})

See the MDN Docs on Array.prototype.filter()

_x000D_
_x000D_
const jsObjects = [_x000D_
  {a: 1, b: 2}, _x000D_
  {a: 3, b: 4}, _x000D_
  {a: 5, b: 6}, _x000D_
  {a: 7, b: 8}_x000D_
]_x000D_
_x000D_
let result = jsObjects.filter(obj => {_x000D_
  return obj.b === 6_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Find the value of the first element/object in the array, otherwise undefined is returned.

var result = jsObjects.find(obj => {
  return obj.b === 6
})

See the MDN Docs on Array.prototype.find()

_x000D_
_x000D_
const jsObjects = [_x000D_
  {a: 1, b: 2}, _x000D_
  {a: 3, b: 4}, _x000D_
  {a: 5, b: 6}, _x000D_
  {a: 7, b: 8}_x000D_
]_x000D_
_x000D_
let result = jsObjects.find(obj => {_x000D_
  return obj.b === 6_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How do you deploy Angular apps?

Simple answer. Use the Angular CLI and issue the

ng build 

command in the root directory of your project. The site will be created in the dist directory and you can deploy that to any web server.

This will build for test, if you have production settings in your app you should use

ng build --prod

This will build the project in the dist directory and this can be pushed to the server.

Much has happened since I first posted this answer. The CLI is finally at a 1.0.0 so following this guide go upgrade your project should happen before you try to build. https://github.com/angular/angular-cli/wiki/stories-rc-update

internal/modules/cjs/loader.js:582 throw err

Caseyjustus comment helped me. Apparently I had space in my require path.

const listingController = require("../controllers/ listingController");

I changed my code to

const listingController = require("../controllers/listingController");

and everything was fine.

Circle drawing with SVG's arc path

Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.

function(cx, cy, r, deg){
    var theta = deg*Math.PI/180,
        dx = r*Math.cos(theta),
        dy = -r*Math.sin(theta);
    return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}

How to sort ArrayList<Long> in decreasing order?

For lamdas where your long value is somewhere in an object I recommend using:

.sorted((o1, o2) -> Long.compare(o1.getLong(), o2.getLong()))

or even better:

.sorted(Comparator.comparingLong(MyObject::getLong))

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

HTML5 event handling(onfocus and onfocusout) using angular 2

If you want to catch the focus event dynamiclly on every input on your component :

import { AfterViewInit, Component, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {

  constructor(private el: ElementRef) {
  }

  ngAfterViewInit() {
       // document.getElementsByTagName('input') : to gell all Docuement imputs
       const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
        inputList.forEach((input: HTMLElement) => {
            input.addEventListener('focus', () => {
                input.setAttribute('placeholder', 'focused');
            });
            input.addEventListener('blur', () => {
                input.removeAttribute('placeholder');
            });
        });
    }
}

Checkout the full code here : https://stackblitz.com/edit/angular-93jdir

TS1086: An accessor cannot be declared in ambient context

I had this error when i deleted several components while the server was on(after running the ng serve command). Although i deleted the references from the routes component and module, it didnt solve the problem. Then i followed these steps:

  1. Ended the server
  2. Restored those files
  3. Ran the ng serve command (at this point it solved the error)
  4. Ended the server
  5. Deleted the components which previously led to the error
  6. Ran the ng serve command (At this point no error as well).

What is <=> (the 'Spaceship' Operator) in PHP 7?

Its a new operator for combined comparison. Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <, <=, ==, >=, >. It returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <, <=, ==, >= and >.

click here to know more

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

You need to use a tool to view the HTTP headers sent with the file, something like LiveHTTPHeaders or HTTPFox are what I use. If the files are sent from the webserver without a MIME type, or with a default MIME type like text/plain, that might be what this error is about.

Floating point comparison functions for C#

Be careful with some answers...

UPDATE 2019-0829, I also included Microsoft decompiled code which should be far better than mine.

1 - You could easily represent any number with 15 significatives digits in memory with a double. See Wikipedia.

2 - The problem come from calculation of floating numbers where you could loose some precision. I mean that a number like .1 could become something like .1000000000000001 ==> after calculation. When you do some calculation, results could be truncated in order to be represented in a double. That truncation brings the error you could get.

3 - To prevent the problem when comparing double values, people introduce an error margin often called epsilon. If 2 floating numbers only have a contextual epsilon as difference, then they are considered equals. double.Epsilon is the smallest number between a double value and its neigbor (next or previous) value.

4 - The difference betwen 2 double values could be more than double.epsilon. The difference between the real double value and the one computed depends on how many calculation you have done and which ones. Many peoples think that it is always double.Epsilon but they are really wrong. To have a great answer please see: Hans Passant answer. The epsilon is based on your context where it depends on the biggest number you reach during your calculation and on the number of calculation you are doing (truncation error accumulate).

5 - This is the code that I use. Be careful that I use my epsilon only for few calculations. Otherwise I multiply my epsilon by 10 or 100.

6 - As noted by SvenL, it is possible that my epsilon is not big enough. I suggest to read SvenL comment. Also, perhaps "decimal" could do the job for your case?

Microsoft decompiled code:

// Decompiled with JetBrains decompiler
// Type: MS.Internal.DoubleUtil
// Assembly: WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: 33C590FB-77D1-4FFD-B11B-3D104CA038E5
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll

using MS.Internal.WindowsBase;
using System;
using System.Runtime.InteropServices;
using System.Windows;

namespace MS.Internal
{
  [FriendAccessAllowed]
  internal static class DoubleUtil
  {
    internal const double DBL_EPSILON = 2.22044604925031E-16;
    internal const float FLT_MIN = 1.175494E-38f;

    public static bool AreClose(double value1, double value2)
    {
      if (value1 == value2)
        return true;
      double num1 = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * 2.22044604925031E-16;
      double num2 = value1 - value2;
      if (-num1 < num2)
        return num1 > num2;
      return false;
    }

    public static bool LessThan(double value1, double value2)
    {
      if (value1 < value2)
        return !DoubleUtil.AreClose(value1, value2);
      return false;
    }

    public static bool GreaterThan(double value1, double value2)
    {
      if (value1 > value2)
        return !DoubleUtil.AreClose(value1, value2);
      return false;
    }

    public static bool LessThanOrClose(double value1, double value2)
    {
      if (value1 >= value2)
        return DoubleUtil.AreClose(value1, value2);
      return true;
    }

    public static bool GreaterThanOrClose(double value1, double value2)
    {
      if (value1 <= value2)
        return DoubleUtil.AreClose(value1, value2);
      return true;
    }

    public static bool IsOne(double value)
    {
      return Math.Abs(value - 1.0) < 2.22044604925031E-15;
    }

    public static bool IsZero(double value)
    {
      return Math.Abs(value) < 2.22044604925031E-15;
    }

    public static bool AreClose(Point point1, Point point2)
    {
      if (DoubleUtil.AreClose(point1.X, point2.X))
        return DoubleUtil.AreClose(point1.Y, point2.Y);
      return false;
    }

    public static bool AreClose(Size size1, Size size2)
    {
      if (DoubleUtil.AreClose(size1.Width, size2.Width))
        return DoubleUtil.AreClose(size1.Height, size2.Height);
      return false;
    }

    public static bool AreClose(Vector vector1, Vector vector2)
    {
      if (DoubleUtil.AreClose(vector1.X, vector2.X))
        return DoubleUtil.AreClose(vector1.Y, vector2.Y);
      return false;
    }

    public static bool AreClose(Rect rect1, Rect rect2)
    {
      if (rect1.IsEmpty)
        return rect2.IsEmpty;
      if (!rect2.IsEmpty && DoubleUtil.AreClose(rect1.X, rect2.X) && (DoubleUtil.AreClose(rect1.Y, rect2.Y) && DoubleUtil.AreClose(rect1.Height, rect2.Height)))
        return DoubleUtil.AreClose(rect1.Width, rect2.Width);
      return false;
    }

    public static bool IsBetweenZeroAndOne(double val)
    {
      if (DoubleUtil.GreaterThanOrClose(val, 0.0))
        return DoubleUtil.LessThanOrClose(val, 1.0);
      return false;
    }

    public static int DoubleToInt(double val)
    {
      if (0.0 >= val)
        return (int) (val - 0.5);
      return (int) (val + 0.5);
    }

    public static bool RectHasNaN(Rect r)
    {
      return DoubleUtil.IsNaN(r.X) || DoubleUtil.IsNaN(r.Y) || (DoubleUtil.IsNaN(r.Height) || DoubleUtil.IsNaN(r.Width));
    }

    public static bool IsNaN(double value)
    {
      DoubleUtil.NanUnion nanUnion = new DoubleUtil.NanUnion();
      nanUnion.DoubleValue = value;
      ulong num1 = nanUnion.UintValue & 18442240474082181120UL;
      ulong num2 = nanUnion.UintValue & 4503599627370495UL;
      if (num1 == 9218868437227405312UL || num1 == 18442240474082181120UL)
        return num2 > 0UL;
      return false;
    }

    [StructLayout(LayoutKind.Explicit)]
    private struct NanUnion
    {
      [FieldOffset(0)]
      internal double DoubleValue;
      [FieldOffset(0)]
      internal ulong UintValue;
    }
  }
}

My code:

public static class DoubleExtension
    {
        // ******************************************************************
        // Base on Hans Passant Answer on:
        // https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre

        /// <summary>
        /// Compare two double taking in account the double precision potential error.
        /// Take care: truncation errors accumulate on calculation. More you do, more you should increase the epsilon.
        public static bool AboutEquals(this double value1, double value2)
        {
            double epsilon = Math.Max(Math.Abs(value1), Math.Abs(value2)) * 1E-15;
            return Math.Abs(value1 - value2) <= epsilon;
        }

        // ******************************************************************
        // Base on Hans Passant Answer on:
        // https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre

        /// <summary>
        /// Compare two double taking in account the double precision potential error.
        /// Take care: truncation errors accumulate on calculation. More you do, more you should increase the epsilon.
        /// You get really better performance when you can determine the contextual epsilon first.
        /// </summary>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <param name="precalculatedContextualEpsilon"></param>
        /// <returns></returns>
        public static bool AboutEquals(this double value1, double value2, double precalculatedContextualEpsilon)
        {
            return Math.Abs(value1 - value2) <= precalculatedContextualEpsilon;
        }

        // ******************************************************************
        public static double GetContextualEpsilon(this double biggestPossibleContextualValue)
        {
            return biggestPossibleContextualValue * 1E-15;
        }

        // ******************************************************************
        /// <summary>
        /// Mathlab equivalent
        /// </summary>
        /// <param name="dividend"></param>
        /// <param name="divisor"></param>
        /// <returns></returns>
        public static double Mod(this double dividend, double divisor)
        {
            return dividend - System.Math.Floor(dividend / divisor) * divisor;
        }

        // ******************************************************************
    }

Create a custom callback in JavaScript

My 2 cent. Same but different...

<script>
    dosomething("blaha", function(){
        alert("Yay just like jQuery callbacks!");
    });


    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function") 
        callback();
    }
</script>

Using scp to copy a file to Amazon EC2 instance?

I tried all the suggestions mentioned above and nothing worked. I terminated the current instance, launched another one and repeated the same exact process. This time no problems. Sometimes it might be the remote ami's fault.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

This error could be thrown in the following situation as well.

You want to checkout branch called feature from remote repository but the error is thrown because you already have branch called feature/<feature_name> in your local repository.

Simply checkout the feature branch under a different name:

git checkout -b <new_branch_name> <remote>/feature

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

Bootstrap control with multiple "data-toggle"

Just for complement @Roman Holzner answer...

In my case, I have a button that shows the tooltip and it should remain disabled until furthermore actions. Using his approach, the modal works even if the button is disabled, because its call is outside the button - I'm in a Laravel blade file, just to be clear :)

<span data-toggle="modal" data-target="#confirm-delete" data-href="{{ $e->id }}">
    <button name="delete" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Excluir Entrada" disabled>
        <i class="fa fa-trash fa-fw"></i>
    </button>
</span>

So if you want to show the modal only when the button is active, you should change the order of the tags:

<span data-toggle="tooltip" data-placement="bottom" title="Excluir Entrada" disabled>
    <button name="delete" class="btn btn-default" data-href="{{ $e->id }}" data-toggle="modal" data-target="#confirm-delete" disabled>
        <i class="fa fa-trash fa-fw"></i>
    </button>
</span>

If you want to test it out, change the attribute with a JQuery code:

$('button[name=delete]').attr('disabled', false);

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Jaqen H'ghar is spot-on. A third way is to:

  1. Go to Manage NuGet Packages
  2. Install Microsoft.jQuery.Unobtrusive.Validation
  3. Open Global.asax.cs file and add this code inside the Application_Start method

Code that runs on application startup:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
    Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
    DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});

how to make a div to wrap two float divs inside?

Aside from the clear: both hack, you can skip the extra element and use overflow: hidden on the wrapping div:

<div style="overflow: hidden;">
    <div style="float: left;"></div>
    <div style="float: left;"></div>
</div>

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

Can you get the number of lines of code from a GitHub repository?

Firefox add-on Github SLOC

I wrote a small firefox addon that prints the number of lines of code on github project pages: Github SLOC

Content Security Policy: The page's settings blocked the loading of a resource

With my ASP.NET Core Angular project running in Visual Studio 2019, sometimes I get this error message in the Firefox console:

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”).

In Chrome, the error message is instead:

Failed to load resource: the server responded with a status of 404 ()

In my case it had nothing to do with my Content Security Policy, but instead was simply the result of a TypeScript error on my part.

Check your IDE output window for a TypeScript error, like:

> ERROR in src/app/shared/models/person.model.ts(8,20): error TS2304: Cannot find name 'bool'.
>
> i ?wdm?: Failed to compile.

Note: Since this question is the first result on Google for this error message.

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

How can I get the IP address from NIC in Python?

If you only need to work on Unix, you can use a system call (ref. Stack Overflow question Parse ifconfig to get only my IP address using Bash):

import os
f = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
your_ip=f.read()

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I got this error from my background service. I solved which creating a new scope.

                using (var scope = serviceProvider.CreateScope())
                {
                      // Process
                }

Difference between HashSet and HashMap?

HashSet allows us to store objects in the set where as HashMap allows us to store objects on the basis of key and value. Every object or stored object will be having key.

SQL join: selecting the last records in a one-to-many relationship

Without getting into the code first, the logic/algorithm goes below:

  1. Go to the transaction table with multiple records for the same client.

  2. Select records of clientID and the latestDate of client's activity using group by clientID and max(transactionDate)

       select clientID, max(transactionDate) as latestDate 
       from transaction 
       group by clientID
    
  3. inner join the transaction table with the outcome from Step 2, then you will have the full records of the transaction table with only each client's latest record.

       select * from 
       transaction t 
       inner join (
         select clientID, max(transactionDate) as latestDate
         from transaction 
         group by clientID) d 
       on t.clientID = d.clientID and t.transactionDate = d.latestDate) 
    
  4. You can use the result from step 3 to join any table you want to get different results.

What is the difference between null and undefined in JavaScript?

null is a special value meaning "no value". null is a special object because typeof null returns 'object'.

On the other hand, undefined means that the variable has not been declared, or has not been given a value.

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

Implement an input with a mask

Use this to implement mask:

https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js

<input id="phn-number" class="ant-input" type="text" placeholder="(XXX) XXX-XXXX" data-inputmask-mask="(999) 999-9999">


jQuery( '#phn-number[data-inputmask-mask]' ).inputmask();

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

Remove spaces from a string in VB.NET

You can also use a small function that will loop through and remove any spaces.

This is very clean and simple.

Public Shared Function RemoveXtraSpaces(strVal As String) As String
     Dim iCount As Integer = 1
     Dim sTempstrVal As String

     sTempstrVal = ""

     For iCount = 1 To Len(strVal)
        sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
     Next

     RemoveXtraSpaces = sTempstrVal

     Return RemoveXtraSpaces

End Function

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

How do I print a double value with full precision using cout?

IEEE 754 floating point values are stored using base 2 representation. Any base 2 number can be represented as a decimal (base 10) to full precision. None of the proposed answers, however, do. They all truncate the decimal value.

This seems to be due to a misinterpretation of what std::numeric_limits<T>::max_digits10 represents:

The value of std::numeric_limits<T>::max_digits10 is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type T.

In other words: It's the (worst-case) number of digits required to output if you want to roundtrip from binary to decimal to binary, without losing any information. If you output at least max_digits10 decimals and reconstruct a floating point value, you are guaranteed to get the exact same binary representation you started with.

What's important: max_digits10 in general neither yields the shortest decimal, nor is it sufficient to represent the full precision. I'm not aware of a constant in the C++ Standard Library that encodes the maximum number of decimal digits required to contain the full precision of a floating point value. I believe it's something like 767 for doubles1. One way to output a floating point value with full precision would be to use a sufficiently large value for the precision, like so2, and have the library strip any trailing zeros:

#include <iostream>

int main() {
    double d = 0.1;
    std::cout.precision(767);
    std::cout << "d = " << d << std::endl;
}

This produces the following output, that contains the full precision:

d = 0.1000000000000000055511151231257827021181583404541015625

Note that this has significantly more decimals than max_digits10 would suggest.


While that answers the question that was asked, a far more common goal would be to get the shortest decimal representation of any given floating point value, that retains all information. Again, I'm not aware of any way to instruct the Standard I/O library to output that value. Starting with C++17 the possibility to do that conversion has finally arrived in C++ in the form of std::to_chars. By default, it produces the shortest decimal representation of any given floating point value that retains the entire information.

Its interface is a bit clunky, and you'd probably want to wrap this up into a function template that returns something you can output to std::cout (like a std::string), e.g.

#include <charconv>
#include <array>
#include <string>
#include <system_error>

#include <iostream>
#include <cmath>

template<typename T>
std::string to_string(T value)
{
    // 24 characters is the longest decimal representation of any double value
    std::array<char, 24> buffer {};
    auto const res { std::to_chars(buffer.data(), buffer.data() + buffer.size(), value) };
    if (res.ec == std::errc {})
    {
        // Success
        return std::string(buffer.data(), res.ptr);
    }

    // Error
    return { "FAILED!" };
}

int main()
{
    auto value { 0.1f };
    std::cout << to_string(value) << std::endl;
    value = std::nextafter(value, INFINITY);
    std::cout << to_string(value) << std::endl;
    value = std::nextafter(value, INFINITY);
    std::cout << to_string(value) << std::endl;
}

This would print out (using Microsoft's C++ Standard Library):

0.1
0.10000001
0.10000002

1 From Stephan T. Lavavej's CppCon 2019 talk titled Floating-Point <charconv>: Making Your Code 10x Faster With C++17's Final Boss. (The entire talk is worth watching.)

2 This would also require using a combination of scientific and fixed, whichever is shorter. I'm not aware of a way to set this mode using the C++ Standard I/O library.

How to check certificate name and alias in keystore files?

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore <FileName>.keystore

Parse date without timezone javascript

You can use this code

var stringDate = "2005-07-08T00:00:00+0000";
var dTimezone = new Date();
var offset = dTimezone.getTimezoneOffset() / 60;
var date = new Date(Date.parse(stringDate));
date.setHours(date.getHours() + offset);

Is there a way to crack the password on an Excel VBA Project?

I tried some of solutions above and none of them works for me (excel 2007 xlsm file). Then i found another solution that even retrieve password, not just crack it.

Insert this code into module, run it and give it some time. It will recover your password by brute force.

Sub PasswordBreaker()

'Breaks worksheet password protection.

Dim i As Integer, j As Integer, k As Integer
Dim l As Integer, m As Integer, n As Integer
Dim i1 As Integer, i2 As Integer, i3 As Integer
Dim i4 As Integer, i5 As Integer, i6 As Integer
On Error Resume Next
For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
If ActiveSheet.ProtectContents = False Then
MsgBox "One usable password is " & Chr(i) & Chr(j) & _
Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
Exit Sub
End If
Next: Next: Next: Next: Next: Next
Next: Next: Next: Next: Next: Next
End Sub

Sending email with PHP from an SMTP server

For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.

PHP regular expression - filter number only

use built in php function is_numeric to check if the value is numeric.

How do I get the directory from a file's full path?

First, you have to use System.IO namespace. Then;

string filename = @"C:\MyDirectory\MyFile.bat";
string newPath = Path.GetFullPath(fileName);

or

string newPath = Path.GetFullPath(openFileDialog1.FileName));

console.log showing contents of array object

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.

How to Get Element By Class in JavaScript?

This code should work in all browsers.

function replaceContentInContainer(matchClass, content) {
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
                > -1) {
            elems[i].innerHTML = content;
        }
    }
}

The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.

jsFiddle Example, using Vanilla JS (i.e. no framework)

What does "<>" mean in Oracle

It means 'not equal to'. So you're filtering out records where ordid is 605. Overall you're looking for any records which have the same prodid and qty values as those assigned to ordid 605, but which are for a different order.

denied: requested access to the resource is denied : docker

Try sign out of "Docker for Windows" application and sign out of https://hub.docker.com/ site and after perform "docker login" and "docker push". It helped for me.

How can I check if a program exists from a Bash script?

It could be simpler, just:

#!/usr/bin/env bash                                                                
set -x                                                                             

# if local program 'foo' returns 1 (doesn't exist) then...                                                                               
if ! type -P foo; then                                                             
    echo 'crap, no foo'                                                            
else                                                                               
    echo 'sweet, we have foo!'                                                    
fi                                                                                 

Change foo to vi to get the other condition to fire.

Determine if char is a num or letter

<ctype.h> includes a range of functions for determining if a char represents a letter or a number, such as isalpha, isdigit and isalnum.

The reason why int a = (int)theChar won't do what you want is because a will simply hold the integer value that represents a specific character. For example the ASCII number for '9' is 57, and for 'a' it's 97.

Also for ASCII:

  • Numeric - if (theChar >= '0' && theChar <= '9')
  • Alphabetic -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

Take a look at an ASCII table to see for yourself.

How can I slice an ArrayList out of an ArrayList in Java?

In Java, it is good practice to use interface types rather than concrete classes in APIs.

Your problem is that you are using ArrayList (probably in lots of places) where you should really be using List. As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList.

This is what your code should look like:

List input = new ArrayList(...);

public void doSomething(List input) {
   List inputA = input.subList(0, input.size()/2);
   ...
}

this.doSomething(input);

Your proposed "solution" to the problem was/is this:

new ArrayList(input.subList(0, input.size()/2))

That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.


If you are constrained by APIs that you cannot change, such that you have to declare inputA as an ArrayList, you might be able to implement a custom subclass of ArrayList in which the subList method returns a subclass of ArrayList. However:

  1. It would be a lot of work to design, implement and test.
  2. You have now added significant new class to your code base, possibly with dependencies on undocumented aspects (and therefore "subject to change") aspects of the ArrayList class.
  3. You would need to change relevant places in your codebase where you are creating ArrayList instances to create instances of your subclass instead.

The "copy the array" solution is more practical ... bearing in mind that these are not true slices.

What is the purpose of XSD files?

XSDs constrain the vocabulary and structure of XML documents.

  • Without an XSD, an XML document need only follow the rules for being well-formed as given in the W3C XML Recommendation.
  • With an XSD, an XML document must adhere to additional constraints placed upon the names and values of its elements and attributes in order to be considered valid against the XSD per the W3C XML Schema Recommendation.

XML is all about agreement, and XSDs provide the means for structuring and communicating the agreement beyond the basic definition of XML itself.

MySQL default datetime through phpmyadmin

The best way for DateTime is use a Trigger:

/************ ROLE ************/
drop table if exists `role`;
create table `role` (
    `id_role` bigint(20) unsigned not null auto_increment,
    `date_created` datetime,
    `date_deleted` datetime,
    `name` varchar(35) not null,
    `description` text,
    primary key (`id_role`)
) comment='';

drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
    on `role`
    for each row 
    set new.`date_created` = now();

Using NSPredicate to filter an NSArray based on NSDictionary keys

I know it's old news but to add my two cents. By default I use the commands LIKE[cd] rather than just [c]. The [d] compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d] strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name where object.name == @"voodoo" will return the object containing the name Vòódòó.

From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.

A function to convert null to string

You can use Convert.ToString((object)value). You need to cast your value to an object first, otherwise the conversion will result in a null.

using System;

public class Program
{
    public static void Main()
    {
        string format = "    Convert.ToString({0,-20}) == null? {1,-5},  == empty? {2,-5}";
        object nullObject = null;
        string nullString = null;

        string convertedString = Convert.ToString(nullObject);
        Console.WriteLine(format, "nullObject", convertedString == null, convertedString == "");

        convertedString = Convert.ToString(nullString);
        Console.WriteLine(format, "nullString", convertedString == null, convertedString == "");

        convertedString = Convert.ToString((object)nullString);
        Console.WriteLine(format, "(object)nullString", convertedString == null, convertedString == "");

    }
}

Gives:

Convert.ToString(nullObject          ) == null? False,  == empty? True 
Convert.ToString(nullString          ) == null? True ,  == empty? False
Convert.ToString((object)nullString  ) == null? False,  == empty? True

If you pass a System.DBNull.Value to Convert.ToString() it will be converted to an empty string too.

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I'm not sure if this is helping you, but I guess that when you do a svn add mysql after you've deleted it it will just reinstantiate the directory (so don't do a mkdir yourself). If you create a directory yourself svn expects a .svn directory inside it because it already 'knows' about it.

Does Python's time.time() return the local or UTC timestamp?

There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.

Java - Search for files in a directory

With **Java 8* there is an alternative that use streams and lambdas:

public static void recursiveFind(Path path, Consumer<Path> c) {
  try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
    StreamSupport.stream(newDirectoryStream.spliterator(), false)
                 .peek(p -> {
                   c.accept(p);
                   if (p.toFile()
                        .isDirectory()) {
                     recursiveFind(p, c);
                   }
                 })
                 .collect(Collectors.toList());
  } catch (IOException e) {
    e.printStackTrace();
  }
}

So this will print all the files recursively:

recursiveFind(Paths.get("."), System.out::println);

And this will search for a file:

recursiveFind(Paths.get("."), p -> { 
  if (p.toFile().getName().toString().equals("src")) {
    System.out.println(p);
  }
});

appending array to FormData and send via AJAX

add all type inputs to FormData

const formData = new FormData();
for (let key in form) {
    Array.isArray(form[key])
        ? form[key].forEach(value => formData.append(key + '[]', value))
        : formData.append(key, form[key]) ;
}

Get name of object or class

If you use standard IIFE (for example with TypeScript)

var Zamboch;
(function (_Zamboch) {
    (function (Web) {
        (function (Common) {
            var App = (function () {
                function App() {
                }
                App.prototype.hello = function () {
                    console.log('Hello App');
                };
                return App;
            })();
            Common.App = App;
        })(Web.Common || (Web.Common = {}));
        var Common = Web.Common;
    })(_Zamboch.Web || (_Zamboch.Web = {}));
    var Web = _Zamboch.Web;
})(Zamboch || (Zamboch = {}));

you could annotate the prototypes upfront with

setupReflection(Zamboch, 'Zamboch', 'Zamboch');

and then use _fullname and _classname fields.

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);

annotating function here:

function setupReflection(ns, fullname, name) {
    // I have only classes and namespaces starting with capital letter
    if (name[0] >= 'A' && name[0] &lt;= 'Z') {
        var type = typeof ns;
        if (type == 'object') {
            ns._refmark = ns._refmark || 0;
            ns._fullname = fullname;
            var keys = Object.keys(ns);
            if (keys.length != ns._refmark) {
                // set marker to avoid recusion, just in case 
                ns._refmark = keys.length;
                for (var nested in ns) {
                    var nestedvalue = ns[nested];
                    setupReflection(nestedvalue, fullname + '.' + nested, nested);
                }
            }
        } else if (type == 'function' && ns.prototype) {
            ns._fullname = fullname;
            ns._classname = name;
            ns.prototype._fullname = fullname;
            ns.prototype._classname = name;
        }
    }
}

JsFiddle

How to add icon inside EditText view in Android ?

Use a relative layout and set the button the be align left of the edit text view, and set the left padding of your text view to the size of your button. I can't think of a good way to do it without hard coding the padding :/

You can also use apk tool to sorta unzip the facebook apk and take a look at its layout files.

What is the most useful script you've written for everyday life?

I don't have the code any more, but possibly the most useful script I wrote was, believe it or not, in VBA. I had an annoying colleague who had such a short fuse that I referred to him as Cherry Bomb. He would often get mad when customers would call and then stand up and start ranting at me over the cubicle wall, killing my productivity and morale.

I always had Microsoft Excel open. When he would do this, I would alt-tab to Excel and there, on the toolbar, was a new icon with an image of a cherry bomb. I would discreetly click that ... and nothing would happen.

However, shortly after that I would get a phone call and would say something like "yeah, yeah, that sounds bad. I had better take a look." And then I would get up, apologize to the Cherry Bomb and walk away.

What happened is that we used NetWare and it had a primitive messaging system built in. When I clicked the button, a small VBA script would send out a NetWare message to my friends, telling them that the Cherry Bomb was at it again and would they please call me. He never figured it out :)

Vim: How to insert in visual block mode?

Try this

After selecting a block of text, press Shift+i or capital I.

Lowercase i will not work.

Then type the things you want and finally to apply it to all lines, press Esc twice.




If this doesn't work...

Check if you have +visualextra enabled in your version of Vim.

You can do this by typing in :ver and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)

Enabling it is outside the scope of this question but I'm sure you can find it somewhere.

How to select the first, second, or third element with a given class name?

Use CSS nth-child with the prefix class name

div.myclass:nth-child(1) {
  color: #000;
}

div.myclass:nth-child(2) {
  color: #FFF;
}

div.myclass:nth-child(3) {
  color: #006;
}

How can I throw CHECKED exceptions from inside Java 8 streams?

You can also write a wrapper method to wrap unchecked exceptions, and even enhance wrapper with additional parameter representing another functional interface (with the same return type R). In this case you can pass a function that would be executed and returned in case of exceptions. See example below:

private void run() {
    List<String> list = Stream.of(1, 2, 3, 4).map(wrapper(i ->
            String.valueOf(++i / 0), i -> String.valueOf(++i))).collect(Collectors.toList());
    System.out.println(list.toString());
}

private <T, R, E extends Exception> Function<T, R> wrapper(ThrowingFunction<T, R, E> function, 
Function<T, R> onException) {
    return i -> {
        try {
            return function.apply(i);
        } catch (ArithmeticException e) {
            System.out.println("Exception: " + i);
            return onException.apply(i);
        } catch (Exception e) {
            System.out.println("Other: " + i);
            return onException.apply(i);
        }
    };
}

@FunctionalInterface
interface ThrowingFunction<T, R, E extends Exception> {
    R apply(T t) throws E;
}

How do I run a spring boot executable jar in a Production environment?

On Windows OS without Service.

start.bat

@ECHO OFF
call run.bat start

stop.bat:

@ECHO OFF
call run.bat stop

run.bat

@ECHO OFF
IF "%1"=="start" (
    ECHO start myapp
    start "myapp" java -jar -Dspring.profiles.active=staging myapp.jar
) ELSE IF "%1"=="stop" (
    ECHO stop myapp
    TASKKILL /FI "WINDOWTITLE eq myapp"
) ELSE (
    ECHO please, use "run.bat start" or "run.bat stop"
)
pause

Can I mask an input text in a bat file?

make a batch file that calls the one needed for invisible characters then make a shortcut for the batch file being called.

right click

properties

colors

text==black

background == black

apply

ok

hope thus helps you!!!!!!!!

What is the HTML5 equivalent to the align attribute in table cells?

you can use this code as replacement for table align

table 
{
    margin:auto;
}

How to open my files in data_folder with pandas using relative path?

Keeping things tidy with f-strings:

import os
import pandas as pd

data_files = '../data_folder/'
csv_name = 'data.csv'

pd.read_csv(f"{data_files}{csv_name}")

How can I introduce multiple conditions in LIKE operator?

SELECT * From tbl WHERE col LIKE '[0-9,a-z]%';

simply use this condition of like in sql and you will get your desired answer

print variable and a string in python

Assuming you use Python 2.7 (not 3):

print "I have", card.price (as mentioned above).

print "I have %s" % card.price (using string formatting)

print " ".join(map(str, ["I have", card.price])) (by joining lists)

There are a lot of ways to do the same, actually. I would prefer the second one.

How to format a phone number with jQuery

Quick roll your own code:

Here is a solution modified from Cruz Nunez's solution above.

// Used to format phone number
function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length < 7) {
      number = number.replace(/(\d{0,3})(\d{0,3})/, "($1) $2");
    } else if (number.length <= 10) {
    number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
    } else {
    // ignore additional digits
    number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
    }
    $(this).val(number)
  });
};

$(phoneFormatter);

JSFiddle

  • In this solution, the formatting is applied no matter how many digits the user has entered. (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.)

  • It requires the zip code for a 10-digit US phone number to be entered.

  • Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.

  • I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:

Recommend jQuery Mask Plugin

I recommend using jQuery Mask Plugin (page has live examples), on github.
These links have minimal explanations on how to use:

CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script CDN Link for jQuery Mask Plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

or
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

WordPress Contact Form 7: use Masks Form Fields plugin

If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.
Masks Form Fields plugin is one option that makes this easy to do.
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.

Example usage on a Contact Form 7 form:

<label> Your Phone Number (required)
    [tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>

The important part here is class:phone_us.
Note that if you use minlength/maxlength, the length must include the mask characters, in addition to the digits.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

How to determine whether a Pandas Column contains a particular value

I did a few simple tests:

In [10]: x = pd.Series(range(1000000))

In [13]: timeit 999999 in x.values
567 µs ± 25.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [15]: timeit x.isin([999999]).any()
9.54 ms ± 291 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [16]: timeit (x == 999999).any()
6.86 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [17]: timeit 999999 in set(x)
79.8 ms ± 1.98 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [21]: timeit x.eq(999999).any()
7.03 ms ± 33.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [22]: timeit x.eq(9).any()
7.04 ms ± 60 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [24]: timeit 9 in x.values
666 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Interestingly it doesn't matter if you look up 9 or 999999, it seems like it takes about the same amount of time using the in syntax (must be using binary search)

In [24]: timeit 9 in x.values
666 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [25]: timeit 9999 in x.values
647 µs ± 5.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [26]: timeit 999999 in x.values
642 µs ± 2.11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [27]: timeit 99199 in x.values
644 µs ± 5.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [28]: timeit 1 in x.values
667 µs ± 20.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Seems like using x.values is the fastest, but maybe there is a more elegant way in pandas?

How to retrieve a file from a server via SFTP?

hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)

Example code from SFTPUpload.java

package net.schmizz.sshj.examples;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.File;
import java.io.IOException;

/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {

    public static void main(String[] args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();
        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final String src = System.getProperty("user.home") + File.separator + "test_file";
            final SFTPClient sftp = ssh.newSFTPClient();
            try {
                sftp.put(new FileSystemFile(src), "/tmp");
            } finally {
                sftp.close();
            }
        } finally {
            ssh.disconnect();
        }
    }

}

How to delete duplicate rows in SQL Server?

It can be done by many ways in sql server the most simplest way to do so is: Insert the distinct rows from the duplicate rows table to new temporary table. Then delete all the data from duplicate rows table then insert all data from temporary table which has no duplicates as shown below.

select distinct * into #tmp From table
   delete from table
   insert into table
   select * from #tmp drop table #tmp

   select * from table

Delete duplicate rows using Common Table Expression(CTE)

With CTE_Duplicates as 
(select id,name , row_number() 
over(partition by id,name order by id,name ) rownumber  from table  ) 
delete from CTE_Duplicates where rownumber!=1

How to show text in combobox when no item selected?

Make the Dropdownstyle property of combo box to Dropdown and set the combo box text to "Select" as below

            combobox.DataSource = dsIn.Tables[0];
            combobox.DisplayMember = "Name";
            combobox.ValueMember = "Value";
            combobox.Text = "--Select--";

Get length of array?

Try CountA:

Dim myArray(1 to 10) as String
Dim arrayCount as String
arrayCount = Application.CountA(myArray)
Debug.Print arrayCount

How to force link from iframe to be opened in the parent window

As noted, you could use a target attribute, but it was technically deprecated in XHTML. That leaves you with using javascript, usually something like parent.window.location.

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

I found this question after seeing the 'more than one device' error, with 2 offline phones showing:

C:\Program Files (x86)\Android\android-sdk\android-tools>adb devices
List of devices attached
SH436WM01785    offline
SH436WM01785    offline
SH436WM01785    sideload

If you only have one device connected, run the following commands to get rid of the offline connections:

adb kill-server
adb devices

Enabling SSL with XAMPP

For XAMPP, do the following steps:

  1. G:\xampp\apache\conf\extra\httpd-ssl.conf"

  2. Search 'DocumentRoot' text.

  3. Change DocumentRoot DocumentRoot "G:/xampp/htdocs" to DocumentRoot "G:/xampp/htdocs/project name".

How does JavaScript .prototype work?

In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.

Example:

_x000D_
_x000D_
//Define a functional object to hold persons in JavaScript_x000D_
var Person = function(name) {_x000D_
  this.name = name;_x000D_
};_x000D_
_x000D_
//Add dynamically to the already defined object a new getter_x000D_
Person.prototype.getName = function() {_x000D_
  return this.name;_x000D_
};_x000D_
_x000D_
//Create a new object of type Person_x000D_
var john = new Person("John");_x000D_
_x000D_
//Try the getter_x000D_
alert(john.getName());_x000D_
_x000D_
//If now I modify person, also John gets the updates_x000D_
Person.prototype.sayMyName = function() {_x000D_
  alert('Hello, my name is ' + this.getName());_x000D_
};_x000D_
_x000D_
//Call the new method on john_x000D_
john.sayMyName();
_x000D_
_x000D_
_x000D_

Until now I've been extending the base object, now I create another object and then inheriting from Person.

//Create a new object of type Customer by defining its constructor. It's not 
//related to Person for now.
var Customer = function(name) {
    this.name = name;
};

//Now I link the objects and to do so, we link the prototype of Customer to 
//a new instance of Person. The prototype is the base that will be used to 
//construct all new instances and also, will modify dynamically all already 
//constructed objects because in JavaScript objects retain a pointer to the 
//prototype
Customer.prototype = new Person();     

//Now I can call the methods of Person on the Customer, let's try, first 
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();

//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
    return this.amountDue;
};

//Let's try:       
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());

_x000D_
_x000D_
var Person = function (name) {_x000D_
    this.name = name;_x000D_
};_x000D_
Person.prototype.getName = function () {_x000D_
    return this.name;_x000D_
};_x000D_
var john = new Person("John");_x000D_
alert(john.getName());_x000D_
Person.prototype.sayMyName = function () {_x000D_
    alert('Hello, my name is ' + this.getName());_x000D_
};_x000D_
john.sayMyName();_x000D_
var Customer = function (name) {_x000D_
    this.name = name;_x000D_
};_x000D_
Customer.prototype = new Person();_x000D_
_x000D_
var myCustomer = new Customer('Dream Inc.');_x000D_
myCustomer.sayMyName();_x000D_
Customer.prototype.setAmountDue = function (amountDue) {_x000D_
    this.amountDue = amountDue;_x000D_
};_x000D_
Customer.prototype.getAmountDue = function () {_x000D_
    return this.amountDue;_x000D_
};_x000D_
myCustomer.setAmountDue(2000);_x000D_
alert(myCustomer.getAmountDue());
_x000D_
_x000D_
_x000D_

While as said I can't call setAmountDue(), getAmountDue() on a Person.

//The following statement generates an error.
john.setAmountDue(1000);

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Phonegap is pretty slow: clicking a button can take up to 3 sec to display the next screen. iscroll is slow and jumpy.

There other funny bugs and issues that i was able to overcome, but in total - not fully matured.

EDIT: Per Grumpy comment, it is not Phonegap who is actually slow, it is the JS/Browser native engine

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

How to write JUnit test with Spring Autowire?

You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
    @Autowired
    private WebApplicationContext wac;
}

Explain the different tiers of 2 tier & 3 tier architecture?

In a modern two-tier architecture, the server holds both the application and the data. The application resides on the server rather than the client, probably because the server will have more processing power and disk space than the PC.

In a three-tier architecture, the data and applications are split onto seperate servers, with the server-side distributed between a database server and an application server. The client is a front end, simply requesting and displaying data. Reason being that each server will be dedicated to processing either data or application requests, hence a more manageable system and less contention for resources will occur.

You can refer to Difference between three tier vs. n-tier

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

How to solve ADB device unauthorized in Android ADB host device?

If anyone has similar issue of having a phone with a cracked screen and has a need to access adb:

  1. Root your phone (mine was already rooted, so I was blessed at least with that).

If you forgot to enable developers mode and your adb isn't running, then do the following:

  1. Reboot your phone into recovery.
  2. Connect the phone with a cable.
  3. Open terminal.
  4. If you type adb devices you should see the device in the list.
  5. If so, type:

    adb shell mount /system
    abd shell
    
    echo "persist.service.adb.enable=1" >> default.prop 
    echo "persist.service.debuggable=1" >> default.prop
    echo "persist.sys.usb.config=mtp,adb" >> default.prop
    echo "persist.service.adb.enable=1" >> /system/build.prop 
    echo "persist.service.debuggable=1" >> /system/build.prop
    echo "persist.sys.usb.config=mtp,adb" >> /system/build.prop
    

Now if you are going to reboot into your phone android will tell you "oh your adb is working but please tap on this OK button, so we can trust your PC". And obviously if we can't tap on the phone stay in the recovery mode and do the following (assuming you are not in the adb shell mode, if so first type exit):

cd ~/.android
adb push adbkey.pub /data/misc/adb/adb_keys
  1. Hurray, it all should be hunky-dory now! Just reboot the phone and you should be able to access adb when the phone is running:

    adb shell reboot

P.S. Was using OS X and Moto X Style that's with the cracked screen.

UL has margin on the left

I don't see any margin or margin-left declarations for #footer-wrap li.

This ought to do the trick:

#footer-wrap ul,
#footer-wrap li {
    margin-left: 0;
    list-style-type: none;
}

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Use the login utility to create a login shell. Assume that the user you want to log in has the username Alice and that zsh is installed in /opt/local/bin/zsh (e.g., a more recent version installed via MacPorts). In iTerm 2, go to Preferences, Profiles, select the profile that you want to set up, and enter in Command:

login -pfq Alice /opt/local/bin/zsh

See man login for more details on the options.

How to check if internet connection is present in Java?

This code should do the job reliably.

Note that when using the try-with-resources statement we don't need to close the resources.

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class InternetAvailabilityChecker
{
    public static boolean isInternetAvailable() throws IOException
    {
        return isHostAvailable("google.com") || isHostAvailable("amazon.com")
                || isHostAvailable("facebook.com")|| isHostAvailable("apple.com");
    }

    private static boolean isHostAvailable(String hostName) throws IOException
    {
        try(Socket socket = new Socket())
        {
            int port = 80;
            InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
            socket.connect(socketAddress, 3000);

            return true;
        }
        catch(UnknownHostException unknownHost)
        {
            return false;
        }
    }
}

Plotting histograms from grouped data in a pandas DataFrame

Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist() it's trying to make a histogram of both columns hence the str error.

This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.

df.reset_index().pivot('index','Letter','N').hist()

The reset_index() is just to shove the current index into a column called index. Then pivot will take your data frame, collect all of the values N for each Letter and make them a column. The resulting data frame as 400 rows (fills missing values with NaN) and three columns (A, B, C). hist() will then produce one histogram per column and you get format the plots as needed.

Checking session if empty or not

Use this if the session variable emp_num will store a string:

 if (!string.IsNullOrEmpty(Session["emp_num"] as string))
 {
                //The code
 }

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.

How to insert an element after another element in JavaScript without using a library?

The method node.after (doc) inserts a node after another node.

For two DOM nodes node1 and node2,

node1.after(node2) inserts node2 after node1.

This method is not available in older browsers, so usually a polyfill is needed.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

After reading your comment on my previous answer I thought I might put this as a separate answer.

Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.

That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with

WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/

This is the jQuery

$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();    
$('.active').show();

    $('#button-next').click(function(){

    $('.active').removeClass('active').addClass('oldActive');    
                   if ( $('.oldActive').is(':last-child')) {
        $('.sp').first().addClass('active');
        }
        else{
        $('.oldActive').next().addClass('active');
        }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();


    });

       $('#button-previous').click(function(){
    $('.active').removeClass('active').addClass('oldActive');    
           if ( $('.oldActive').is(':first-child')) {
        $('.sp').last().addClass('active');
        }
           else{
    $('.oldActive').prev().addClass('active');
           }
    $('.oldActive').removeClass('oldActive');
    $('.sp').fadeOut();
    $('.active').fadeIn();
    });




});

So now the explanation.
Stage 1
1) Load the script on document ready.

2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.

3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;

Stage 2 Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.

2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.

3) We remove the class oldActive because it's no longer needed.

4) fadeOut all of the slides

5) fade In the active slides

Step 3

Same as in step two but using some reverse logic for traversing through the elements backwards.

It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.

Code-first vs Model/Database-first

Quoting the relevant parts from http://www.itworld.com/development/405005/3-reasons-use-code-first-design-entity-framework

3 reasons to use code first design with Entity Framework

1) Less cruft, less bloat

Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code. You’re implored never to touch these generated files lest you break something, or your changes get overwritten on the next generation. The context and initializer are jammed together in this mess as well. When you need to add functionality to your generated models, like a calculated read only property, you need to extend the model class. This ends up being a requirement for almost every model and you end up with an extension for everything.

With code first your hand coded models become your database. The exact files that you’re building are what generate the database design. There are no additional files and there is no need to create a class extension when you want to add properties or whatever else that the database doesn't need to know about. You can just add them into the same class as long as you follow the proper syntax. Heck, you can even generate a Model.edmx file to visualize your code if you want.

2) Greater Control

When you go DB first, you’re at the mercy of what gets generated for your models for use in your application. Occasionally the naming convention is undesirable. Sometimes the relationships and associations aren't quite what you want. Other times non transient relationships with lazy loading wreak havoc on your API responses.

While there is almost always a solution for model generation problems you might run into, going code first gives you complete and fine grained control from the get go. You can control every aspect of both your code models and your database design from the comfort of your business object. You can precisely specify relationships, constraints, and associations. You can simultaneously set property character limits and database column sizes. You can specify which related collections are to be eager loaded, or not be serialized at all. In short, you are responsible for more stuff but you’re in full control of your app design.

3)Database Version Control

This is a big one. Versioning databases is hard, but with code first and code first migrations, it’s much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database. You’re responsible for controlling your context initialization which can help you do things like seed fixed business data. You’re also responsible for creating code first migrations.

When you first enable migrations, a configuration class and an initial migration are generated. The initial migration is your current schema or your baseline v1.0. From that point on you will add migrations which are timestamped and labeled with a descriptor to help with ordering of versions. When you call add-migration from the package manager, a new migration file will be generated containing everything that has changed in your code model automatically in both an UP() and DOWN() function. The UP function applies the changes to the database, the DOWN function removes those same changes in the event you want to rollback. What’s more, you can edit these migration files to add additional changes such as new views, indexes, stored procedures, and whatever else. They will become a true versioning system for your database schema.

What is the difference between React Native and React?

ReactJS is a javascript library which is used to build web interfaces. You would need a bundler like webpack and try to install modules you would need to build your website.

React Native is a javascript framework and it comes with everything you need to write multi-platform apps (like iOS or Android). You would need xcode and android studio installed to build and deploy your app.

Unlike ReactJS, React-Native doesn't use HTML but similar components that you can use accross ios and android to build your app. These components use real native components to build the ios and android apps. Due to this React-Native apps feel real unlike other Hybrid development platforms. Components also increases reusability of your code as you don't need to create same user interface again on ios and android.

What is the Python equivalent of static variables inside a function?

Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. Also see this answer.

class Foo(object):
  # Class variable, shared by all instances of this class
  counter = 0

  def __call__(self):
    Foo.counter += 1
    print Foo.counter

# Create an object instance of class "Foo," called "foo"
foo = Foo()

# Make calls to the "__call__" method, via the object's name itself
foo() #prints 1
foo() #prints 2
foo() #prints 3

Note that __call__ makes an instance of a class (object) callable by its own name. That's why calling foo() above calls the class' __call__ method. From the documentation:

Instances of arbitrary classes can be made callable by defining a __call__() method in their class.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

This answer is not specifically related to Silverlight but the general error: The breakpoint will not currently be hit. No symbols have been loaded for this document. A noob mistake is that the project is not set as debug in configuration manager. Worth a check

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

what is the basic difference between stack and queue?

A stack is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in reverse order of their time of storage, i.e. the latest element stored is the next element to be retrieved. A stack is sometimes referred to as a Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) structure. Elements previously stored cannot be retrieved until the latest element (usually referred to as the 'top' element) has been retrieved.

A queue is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in order of their time of storage, i.e. the first element stored is the next element to be retrieved. A queue is sometimes referred to as a First-In-First-Out (FIFO) or Last-In-Last-Out (LILO) structure. Elements subsequently stored cannot be retrieved until the first element (usually referred to as the 'front' element) has been retrieved.

How to check undefined in Typescript

From Typescript 3.7 on, you can also use nullish coalescing:

let x = foo ?? bar();

Which is the equivalent for checking for null or undefined:

let x = (foo !== null && foo !== undefined) ?
    foo :
    bar();

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

While not exactly the same, you could write your code as:

var uemail = localStorage.getItem("useremail") ?? alert('Undefined');

Convert command line argument to string

You can create an std::string

#include <string>
#include <vector>
int main(int argc, char *argv[])
{
  // check if there is more than one argument and use the second one
  //  (the first argument is the executable)
  if (argc > 1)
  {
    std::string arg1(argv[1]);
    // do stuff with arg1
  }

  // Or, copy all arguments into a container of strings
  std::vector<std::string> allArgs(argv, argv + argc);
}

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I escape a double quote inside double quotes?

Bash allows you to place strings adjacently, and they'll just end up being glued together.

So this:

$ echo "Hello"', world!'

produces

Hello, world!

The trick is to alternate between single and double-quoted strings as required. Unfortunately, it quickly gets very messy. For example:

$ echo "I like to use" '"double quotes"' "sometimes"

produces

I like to use "double quotes" sometimes

In your example, I would do it something like this:

$ dbtable=example
$ dbload='load data local infile "'"'gfpoint.csv'"'" into '"table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"'"'"' LINES "'TERMINATED BY "'"'\n'"'" IGNORE 1 LINES'
$ echo $dbload

which produces the following output:

load data local infile "'gfpoint.csv'" into table example FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "'\n'" IGNORE 1 LINES

It's difficult to see what's going on here, but I can annotate it using Unicode quotes. The following won't work in bash – it's just for illustration:

dbload=load data local infile "’“'gfpoint.csv'”‘" into’“table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '”‘"’“' LINES”‘TERMINATED BY "’“'\n'”‘" IGNORE 1 LINES

The quotes like “ ‘ ’ ” in the above will be interpreted by bash. The quotes like " ' will end up in the resulting variable.

If I give the same treatment to the earlier example, it looks like this:

$ echoI like to use"double quotes"sometimes

Embedding SVG into ReactJS

If you want to load it from a file, you may try to use React-inlinesvg - that's pretty simple and straight-forward.

import SVG from 'react-inlinesvg';

<SVG
  src="/path/to/myfile.svg"
  preloader={<Loader />}
  onLoad={(src) => {
    myOnLoadHandler(src);
  }}
>
  Here's some optional content for browsers that don't support XHR or inline
  SVGs. You can use other React components here too. Here, I'll show you.
  <img src="/path/to/myfile.png" />
</SVG>

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Following worked for me.

  1. Open another instance of Application Loader. ( Select "Application Loader" under the "Xcode -> Open Developer Tool" menu)

  2. "Agree" to the terms.

  3. After completing Step 2. First instance of Application Loader proceeded to the next step and build got submitted.

Can I return the 'id' field after a LINQ insert?

When inserting the generated ID is saved into the instance of the object being saved (see below):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = “Sample Category”;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

how to copy only the columns in a DataTable to another DataTable?

If you want the structure of a particular data table(dataTable1) with column headers (without data) into another data table(dataTable2), you can follow the below code:

        DataTable dataTable2 = dataTable1.Clone();
        dataTable2.Clear();

Now you can fill dataTable2 according to your condition. :)

phpMyAdmin says no privilege to create database, despite logged in as root user

Use these:

  • username : root
  • password : (nothing)

Then you will get the page you want (more options than the admin page) with privileges.

How do I access the HTTP request header fields via JavaScript?

I would imagine Google grabs some data server-side - remember, when a page loads into your browser that has Google Analytics code within it, your browser makes a request to Google's servers; Google can obtain data in that way as well as through the JavaScript embedded in the page.

Copy data from one existing row to another existing row in SQL?

Use SELECT to Insert records

INSERT tracking (userID, courseID, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent) 
SELECT userID, 11, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent
FROM tracking WHERE courseID = 6 AND course_date > '08-01-2008'

String to object in JS

var stringExample = "firstName:name1, lastName:last1 | firstName:name2, lastName:last2";    

var initial_arr_objects = stringExample.split("|");
    var objects =[];
    initial_arr_objects.map((e) => {
          var string = e;
          var fields = string.split(','),fieldObject = {};
        if( typeof fields === 'object') {
           fields.forEach(function(field) {
              var c = field.split(':');
              fieldObject[c[0]] = c[1]; //use parseInt if integer wanted
           });
        }
            console.log(fieldObject)
            objects.push(fieldObject);
        });

"objects" array will have all the objects

Standard deviation of a list

Using python, here are few methods:

import statistics as st

n = int(input())
data = list(map(int, input().split()))

Approach1 - using a function

stdev = st.pstdev(data)

Approach2: calculate variance and take square root of it

variance = st.pvariance(data)
devia = math.sqrt(variance)

Approach3: using basic math

mean = sum(data)/n
variance = sum([((x - mean) ** 2) for x in X]) / n
stddev = variance ** 0.5

print("{0:0.1f}".format(stddev))

Note:

  • variance calculates variance of sample population
  • pvariance calculates variance of entire population
  • similar differences between stdev and pstdev

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

Check/Uncheck checkbox with JavaScript

I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.

So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.

iPhone UILabel text soft shadow

To keep things up to date: Creating the shadow in Swift is as easy as that:

Import the QuartzCore Framework

import QuartzCore

And set the shadow attributes to your label

titleLabel.shadowColor = UIColor.blackColor()
titleLabel.shadowOffset = CGSizeMake(0.0, 0.0)
titleLabel.layer.shadowRadius = 5.0
titleLabel.layer.shadowOpacity = 0.8
titleLabel.layer.masksToBounds = false
titleLabel.layer.shouldRasterize = true

How to filter an array from all elements of another array

The best description to filter function is https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/filter

You should simply condition function:

function conditionFun(element, index, array) {
   return element >= 10;
}
filtered = [12, 5, 8, 130, 44].filter(conditionFun);

And you can't access the variable value before it is assigned

ModuleNotFoundError: No module named 'sklearn'


Brief Introduction


When using Anaconda, one needs to be aware of the environment that one is working.

Then, in Anaconda Prompt (base) one needs to use the following code:

conda $command -n $ENVIRONMENT_NAME $IDE/package/module

$command - Command that I intend to use (consult documentation for general commands)

$ENVIRONMENT NAME - The name of your environment (if one is working in the root, conda $command $IDE/package/module is enough)

$IDE/package/module - The name of the IDE or package or module


Solution


If one wants to install it in the root and one follows the requirements - (Python (>= 2.7 or >= 3.4), NumPy (>= 1.8.2), SciPy (>= 0.13.3).) - the following will solve the problem:

conda install scikit-learn

Let's say that one is working in the environment with the name ML.

Then the following will solve one's problem:

conda install -n ML scikit-learn

Note: If one needs to install/update packages, the logic is the same as mentioned in the introduction. If you need more information on Anaconda Packages, check the documentation.


If the above doesn't work, on Anaconda Prompt one can also use pip (here's how to pip install scikit-learn) so the following may help

pip install scikit-learn

How to select a radio button by default?

Use the checked attribute.

<input type="radio" name="imgsel"  value="" checked /> 

or

<input type="radio" name="imgsel"  value="" checked="checked" /> 

MySQL and PHP - insert NULL rather than empty string

you can do it for example with

UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

Using a remote repository with non-standard port

This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config file and having something like this

Host git_host
HostName git.host.de
User root
Port 4019

then you can have

url = git_host:/var/cache/git/project.git

and you can also ssh git_host and scp git_host ... and everything will work out.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

The first suggestion in latkin's answer seems good, although I would suggest the less long-winded way below.

PS c:\temp> $global:test="one"

PS c:\temp> $test
one

PS c:\temp> function changet() {$global:test="two"}

PS c:\temp> changet

PS c:\temp> $test
two

His second suggestion however about being bad programming practice, is fair enough in a simple computation like this one, but what if you want to return a more complicated output from your variable? For example, what if you wanted the function to return an array or an object? That's where, for me, PowerShell functions seem to fail woefully. Meaning you have no choice other than to pass it back from the function using a global variable. For example:

PS c:\temp> function changet([byte]$a,[byte]$b,[byte]$c) {$global:test=@(($a+$b),$c,($a+$c))}

PS c:\temp> changet 1 2 3

PS c:\temp> $test
3
3
4

PS C:\nb> $test[2]
4

I know this might feel like a bit of a digression, but I feel in order to answer the original question we need to establish whether global variables are bad programming practice and whether, in more complex functions, there is a better way. (If there is one I'd be interested to here it.)

How to make one Observable sequence wait for another to complete before emitting?

If you want to make sure that the order of execution is retained you can use flatMap as the following example

const first = Rx.Observable.of(1).delay(1000).do(i => console.log(i));
const second = Rx.Observable.of(11).delay(500).do(i => console.log(i));
const third = Rx.Observable.of(111).do(i => console.log(i));

first
  .flatMap(() => second)
  .flatMap(() => third)
  .subscribe(()=> console.log('finished'));

The outcome would be:

"1"
"11"
"111"
"finished"

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I also experienced this error.

I add into header Content-Type: application/json. Following the change, my submissions succeed!

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

Compare 2 arrays which returns difference

In this way you don't need to worry about if the first array is smaller than the second one.

var arr1 = [1, 2, 3, 4, 5, 6,10],
    arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function array_diff(array1, array2){
    var difference = $.grep(array1, function(el) { return $.inArray(el,array2) < 0});
    return difference.concat($.grep(array2, function(el) { return $.inArray(el,array1) < 0}));;
}

console.log(array_diff(arr1, arr2));

Getting a File's MD5 Checksum in Java

public static void main(String[] args) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");

    byte[] dataBytes = new byte[1024];

    int nread = 0;
    while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
    };
    byte[] mdbytes = md.digest();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < mdbytes.length; i++) {
        sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
    System.out.println("Digest(in hex format):: " + sb.toString());
}

Or you may get more info http://www.asjava.com/core-java/java-md5-example/

Load image from url

loadImage("http://relinjose.com/directory/filename.png");

Here you go

void loadImage(String image_location) {
    URL imageURL = null;
    if (image_location != null) {
        try {
            imageURL = new URL(image_location);         
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            ivdpfirst.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //set any default
    }
}

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.

  • It Keeps the photos aspect ratio
  • Scales in vertical and horizontal
  • Centers vertically and horizontal
  • The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.

    Give it a try :)

*only tested in chrome so far

HTML:

<div class="frame">
  <img src="image.jpg"/>
</div>

CSS:

.frame {
  border: 1px solid red;

  min-height: 98%;
  max-height: 98%;
  min-width: 99%;
  max-width: 99%;

  text-align: center;
  margin: auto;
  position: absolute;
}
img {
  border: 1px solid blue;

  min-height: 98%;
  max-width: 99%;
  max-height: 98%;

  width: auto;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

How to tackle daylight savings using TimeZone in Java

This is the problem to start with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)

You want a full time zone name. For example, America/New_York is in the Eastern time zone:

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));

Print Currency Number Format in PHP

try

echo "$".money_format('%i',$price);

output will be

$1.06

What does "Use of unassigned local variable" mean?

The compiler isn't smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn't see that variables like annualRate will be assigned no matter what. Here's how you can make the compiler understand:

if (creditPlan == "0")
{
    // ...
}
else if (creditPlan == "1")
{
    // ...
}
else if (creditPlan == "2")
{
    // ...
}
else
{
    // ...
}

The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.

By the way, you can also use a switch statement instead of ifs to maybe make your code cleaner.

Return index of highest value in an array

Other answers may have shorter code but this one should be the most efficient and is easy to understand.

/**
 * Get key of the max value
 *
 * @var array $array
 * @return mixed
*/
function array_key_max_value($array)
{
    $max = null;
    $result = null;
    foreach ($array as $key => $value) {
        if ($max === null || $value > $max) {
            $result = $key;
            $max = $value;
        }
    }

    return $result;
}

HTML / CSS How to add image icon to input type="button"?

<button type="submit" style="background-color:transparent; border-color:transparent;"> 
  <img src="images/button/masuk.png" height="35"/>
</button>
<button type="reset" style="background-color:transparent; border-color:transparent;"> 
  <img src="images/button/reset.png" height="35"/>
</button>

I hope this helps you.

Get The Current Domain Name With Javascript (Not the path, etc.)

window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.

There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:

_x000D_
_x000D_
let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?(\w{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
_x000D_
_x000D_
_x000D_

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

Windows batch: call more than one command in a FOR loop?

FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)

Better way to cast object to int

Convert.ToInt32(myobject);

This will handle the case where myobject is null and return 0, instead of throwing an exception.

How to generate a number of most distinctive colors in R?

Here are a few options:

  1. Have a look at the palette function:

     palette(rainbow(6))     # six color rainbow
     (palette(gray(seq(0,.9,len = 25)))) #grey scale
    
  2. And the colorRampPalette function:

     ##Move from blue to red in four colours
     colorRampPalette(c("blue", "red"))( 4) 
    
  3. Look at the RColorBrewer package (and website). If you want diverging colours, then select diverging on the site. For example,

     library(RColorBrewer)
     brewer.pal(7, "BrBG")
    
  4. The I want hue web site gives lots of nice palettes. Again, just select the palette that you need. For example, you can get the rgb colours from the site and make your own palette:

     palette(c(rgb(170,93,152, maxColorValue=255),
         rgb(103,143,57, maxColorValue=255),
         rgb(196,95,46, maxColorValue=255),
         rgb(79,134,165, maxColorValue=255),
         rgb(205,71,103, maxColorValue=255),
         rgb(203,77,202, maxColorValue=255),
         rgb(115,113,206, maxColorValue=255)))
    

What's the difference between '$(this)' and 'this'?

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:

$(".myCheckboxes").change(function(){ 
    if(this.checked) 
       alert("checked"); 
});

is easier and purer than

$(".myCheckboxes").change(function(){ 
      if($(this).is(":checked")) 
         alert("checked"); 
});

htaccess <Directory> deny from all

You can use from root directory:

RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html

Or:

RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

I have also experienced this issue and problem occurs every time when context of your FragmentActivity gets changed (e.g. Screen orientation is changed, etc.). So the best fix for it is to update context from your FragmentActivity.

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

Does Visual Studio Code have box select/multi-line edit?

The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right

To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu FilePreferencesKeyboard shortcuts).

{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
                                 "when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
                                     "when": "editorTextFocus" }

How to get an object's properties in JavaScript / jQuery?

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}

Usage

alert(simpleObjInspect(anyObject));

or

console.log(simpleObjInspect(anyObject));

How do I left align these Bootstrap form items?

Instead of altering the original bootstrap css class create a new css file that will override the default style.

Make sure you include the new css file after including the bootstrap.css file.

In the new css file do

.form-horizontal .control-label{
   text-align:left !important; 
}

CSS text-overflow: ellipsis; not working?

So if you reach this question because you're having trouble trying to get the ellipsis working inside a display: flex container, try adding min-width: 0 to the outmost container that's overflowing its parent even though you already set a overflow: hidden to it and see how that works for you.

More details and a working example on this codepen by aj-foster. Totally did the trick in my case.

Animate change of view background color on Android

Depending on how your view gets its background color and how you get your target color there are several different ways to do this.

The first two uses the Android Property Animation framework.

Use a Object Animator if:

  • Your view have its background color defined as a argb value in a xml file.
  • Your view have previously had its color set by view.setBackgroundColor()
  • Your view have its background color defined in a drawable that DOES NOT defines any extra properties like stroke or corner radiuses.
  • Your view have its background color defined in a drawable and you want to remove any extra properties like stroke or corner radiuses, keep in mind that the removal of the extra properties will not animated.

The object animator works by calling view.setBackgroundColor which replaces the defined drawable unless is it an instance of a ColorDrawable, which it rarely is. This means that any extra background properties from a drawable like stroke or corners will be removed.

Use a Value Animator if:

  • Your view have its background color defined in a drawable that also sets properties like the stroke or corner radiuses AND you want to change it to a new color that is decided while running.

Use a Transition drawable if:

  • Your view should switch between two drawable that have been defined before deployment.

I have had some performance issues with Transition drawables that runs while I am opening a DrawerLayout that I haven't been able to solve, so if you encounter any unexpected stuttering you might have run into the same bug as I have.

You will have to modify the Value Animator example if you want to use a StateLists drawable or a LayerLists drawable, otherwise it will crash on the final GradientDrawable background = (GradientDrawable) view.getBackground(); line.

Object Animator:

View definition:

<View
    android:background="#FFFF0000"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

Create and use a ObjectAnimator like this.

final ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(view,
                                                                       "backgroundColor",
                                                                       new ArgbEvaluator(),
                                                                       0xFFFFFFFF,
                                                                       0xff78c5f9);
backgroundColorAnimator.setDuration(300);
backgroundColorAnimator.start();

You can also load the animation definition from a xml using a AnimatorInflater like XMight does in Android objectAnimator animate backgroundColor of Layout

Value Animator:

View definition:

<View
    android:background="@drawable/example"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

Drawable definition:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke
        android:color="#edf0f6"
        android:width="1dp"/>
    <corners android:radius="3dp"/>

</shape>

Create and use a ValueAnimator like this:

final ValueAnimator valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(),
                                                           0xFFFFFFFF,
                                                           0xff78c5f9);

final GradientDrawable background = (GradientDrawable) view.getBackground();
currentAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(final ValueAnimator animator) {
        background.setColor((Integer) animator.getAnimatedValue());
    }

});
currentAnimation.setDuration(300);
currentAnimation.start();

Transition drawable:

View definition:

<View
    android:background="@drawable/example"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

Drawable definition:

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="#FFFFFF"/>
            <stroke
                android:color="#edf0f6"
                android:width="1dp"/>
            <corners android:radius="3dp"/>
        </shape>
    </item>

    <item>
        <shape>
            <solid android:color="#78c5f9"/>
            <stroke
                android:color="#68aff4"
                android:width="1dp"/>
            <corners android:radius="3dp"/>
        </shape>
    </item>
</transition>

Use the TransitionDrawable like this:

final TransitionDrawable background = (TransitionDrawable) view.getBackground();
background.startTransition(300);

You can reverse the animations by calling .reverse() on the animation instance.

There are some other ways to do animations but these three is probably the most common. I generally use a ValueAnimator.

ArrayList vs List<> in C#

Performance has already been mentioned in several answers as a differentiating factor, but to address the “How much slower is the ArrayList ?” and “Why is it slower overall ?”, have a look below.

Whenever value types are used as elements, performance drops dramatically with ArrayList. Consider the case of simply adding elements. Due to the boxing going on - as ArrayList’s Add only takes object parameters - the Garbage Collector gets triggered into performing a lot more work than with List<T>.

How much is the time difference ? At least several times slower than with List<T>. Just take a look at what happens with code adding 10 mil int values to an ArrayList vs List<T>: enter image description here

That’s a run time difference of 5x in the ‘Mean’ column, highlighted in yellow. Note also the difference in the number of garbage collections done for each, highlighted in red (no of GCs / 1000 runs).

Using a profiler to see what’s going on quickly shows that most of the time is spent doing GCs, as opposed to actually adding elements. The brown bars below represent blocking Garbage Collector activity: enter image description here

I’ve written a detailed analysis of what goes on with the above ArrayList scenario here https://mihai-albert.com/2019/12/15/boxing-performance-in-c-analysis-and-benchmark/.

Similar findings are in “CLR via C#” by Jeffrey Richter. From chapter 12 (Generics):

[…] When I compile and run a release build (with optimizations turned on) of this program on my computer, I get the following output.

00:00:01.6246959 (GCs= 6) List<Int32>
00:00:10.8555008 (GCs=390) ArrayList of Int32
00:00:02.5427847 (GCs= 4) List<String>
00:00:02.7944831 (GCs= 7) ArrayList of String

The output here shows that using the generic List algorithm with the Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. In fact, the difference is phenomenal: 1.6 seconds versus almost 11 seconds. That’s ~7 times faster! In addition, using a value type (Int32) with ArrayList causes a lot of boxing operations to occur, which results in 390 garbage collections. Meanwhile, the List algorithm required 6 garbage collections.

Difference between `constexpr` and `const`

Basic meaning and syntax

Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this:

  • const declares an object as constant. This implies a guarantee that once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization.

  • constexpr declares an object as fit for use in what the Standard calls constant expressions. But note that constexpr is not the only way to do this.

When applied to functions the basic difference is this:

  • const can only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members (except for mutable data members, which can be modified anyway).

  • constexpr can be used with both member and non-member functions, as well as constructors. It declares the function fit for use in constant expressions. The compiler will only accept it if the function meets certain criteria (7.1.5/3,4), most importantly (†):

    • The function body must be non-virtual and extremely simple: Apart from typedefs and static asserts, only a single return statement is allowed. In the case of a constructor, only an initialization list, typedefs, and static assert are allowed. (= default and = delete are allowed, too, though.)
    • As of C++14, the rules are more relaxed, what is allowed since then inside a constexpr function: asm declaration, a goto statement, a statement with a label other than case and default, try-block, the definition of a variable of non-literal type, definition of a variable of static or thread storage duration, the definition of a variable for which no initialization is performed.
    • The arguments and the return type must be literal types (i.e., generally speaking, very simple types, typically scalars or aggregates)

Constant expressions

As said above, constexpr declares both objects as well as functions as fit for use in constant expressions. A constant expression is more than merely constant:

  • It can be used in places that require compile-time evaluation, for example, template parameters and array-size specifiers:

      template<int N>
      class fixed_size_list
      { /*...*/ };
    
      fixed_size_list<X> mylist;  // X must be an integer constant expression
    
      int numbers[X];  // X must be an integer constant expression
    
  • But note:

  • Declaring something as constexpr does not necessarily guarantee that it will be evaluated at compile time. It can be used for such, but it can be used in other places that are evaluated at run-time, as well.

  • An object may be fit for use in constant expressions without being declared constexpr. Example:

         int main()
         {
           const int N = 3;
           int numbers[N] = {1, 2, 3};  // N is constant expression
         }
    

    This is possible because N, being constant and initialized at declaration time with a literal, satisfies the criteria for a constant expression, even if it isn't declared constexpr.

So when do I actually have to use constexpr?

  • An object like N above can be used as constant expression without being declared constexpr. This is true for all objects that are:
  • const
  • of integral or enumeration type and
  • initialized at declaration time with an expression that is itself a constant expression

[This is due to §5.19/2: A constant expression must not include a subexpression that involves "an lvalue-to-rvalue modification unless […] a glvalue of integral or enumeration type […]" Thanks to Richard Smith for correcting my earlier claim that this was true for all literal types.]

  • For a function to be fit for use in constant expressions, it must be explicitly declared constexpr; it is not sufficient for it merely to satisfy the criteria for constant-expression functions. Example:

     template<int N>
     class list
     { };
    
     constexpr int sqr1(int arg)
     { return arg * arg; }
    
     int sqr2(int arg)
     { return arg * arg; }
    
     int main()
     {
       const int X = 2;
       list<sqr1(X)> mylist1;  // OK: sqr1 is constexpr
       list<sqr2(X)> mylist2;  // wrong: sqr2 is not constexpr
     }
    

When can I / should I use both, const and constexpr together?

A. In object declarations. This is never necessary when both keywords refer to the same object to be declared. constexpr implies const.

constexpr const int N = 5;

is the same as

constexpr int N = 5;

However, note that there may be situations when the keywords each refer to different parts of the declaration:

static constexpr int N = 3;

int main()
{
  constexpr const int *NP = &N;
}

Here, NP is declared as an address constant-expression, i.e. a pointer that is itself a constant expression. (This is possible when the address is generated by applying the address operator to a static/global constant expression.) Here, both constexpr and const are required: constexpr always refers to the expression being declared (here NP), while const refers to int (it declares a pointer-to-const). Removing the const would render the expression illegal (because (a) a pointer to a non-const object cannot be a constant expression, and (b) &N is in-fact a pointer-to-constant).

B. In member function declarations. In C++11, constexpr implies const, while in C++14 and C++17 that is not the case. A member function declared under C++11 as

constexpr void f();

needs to be declared as

constexpr void f() const;

under C++14 in order to still be usable as a const function.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

If you are consuming an internal service via AJAX, make sure the url points to https, this cleared up the error for me.

Initial AJAX URL: "http://XXXXXX.com/Core.svc/" + ApiName
Corrected AJAX URL: "https://XXXXXX.com/Core.svc/" + ApiName,

git commit error: pathspec 'commit' did not match any file(s) known to git

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

Find when a file was deleted in Git

You can find the last commit which deleted file as follows:

git rev-list -n 1 HEAD -- [file_path]

Further information is available here

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

Setting SMTP details for php mail () function

Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider

How to generate a random String in Java

Generating a random string of characters is easy - just use java.util.Random and a string containing all the characters you want to be available, e.g.

public static String generateString(Random rng, String characters, int length)
{
    char[] text = new char[length];
    for (int i = 0; i < length; i++)
    {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

Now, for uniqueness you'll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Ruby capitalize every word first letter

Another option is to use a regex and gsub, which takes a block:

'one TWO three foUR'.gsub(/\w+/, &:capitalize)

Using %s in C correctly - very basic level

%s will get all the values until it gets NULL i.e. '\0'.

char str1[] = "This is the end\0";
printf("%s",str1);

will give

This is the end

char str2[] = "this is\0 the end\0";
printf("%s",str2);

will give

this is

How to Generate Unique Public and Private Key via RSA

What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:

public static string ConvertToNewKey(string oldPrivateKey)
{

    // get the current container name from the database...

    rsa.PersistKeyInCsp = false;
    rsa.Clear();
    rsa = null;

    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...

       // re-encrypt existing data to use the new keys and write to database...

    return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
     string containerName = DateTime.Now.Ticks.ToString();
     // create the new key...
     // saves container name and public key to database...
     // and returns Private Key XML.
}

before creating the new key.

Programmatically getting the MAC of an Android device

You can get mac address:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();

Set Permission in Menifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

Javac is not found

You don't have jdk1.7.0_17 in your PATH - check again. There is only JRE which may not contain 'javac' compiler.

Besides it is best to set JAVA_HOME variable, and then include it in PATH.

Recommended way of making React component/div draggable

I've updated polkovnikov.ph solution to React 16 / ES6 with enhancements like touch handling and snapping to a grid which is what I need for a game. Snapping to a grid alleviates the performance issues.

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';

class Draggable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            relX: 0,
            relY: 0,
            x: props.x,
            y: props.y
        };
        this.gridX = props.gridX || 1;
        this.gridY = props.gridY || 1;
        this.onMouseDown = this.onMouseDown.bind(this);
        this.onMouseMove = this.onMouseMove.bind(this);
        this.onMouseUp = this.onMouseUp.bind(this);
        this.onTouchStart = this.onTouchStart.bind(this);
        this.onTouchMove = this.onTouchMove.bind(this);
        this.onTouchEnd = this.onTouchEnd.bind(this);
    }

    static propTypes = {
        onMove: PropTypes.func,
        onStop: PropTypes.func,
        x: PropTypes.number.isRequired,
        y: PropTypes.number.isRequired,
        gridX: PropTypes.number,
        gridY: PropTypes.number
    }; 

    onStart(e) {
        const ref = ReactDOM.findDOMNode(this.handle);
        const body = document.body;
        const box = ref.getBoundingClientRect();
        this.setState({
            relX: e.pageX - (box.left + body.scrollLeft - body.clientLeft),
            relY: e.pageY - (box.top + body.scrollTop - body.clientTop)
        });
    }

    onMove(e) {
        const x = Math.trunc((e.pageX - this.state.relX) / this.gridX) * this.gridX;
        const y = Math.trunc((e.pageY - this.state.relY) / this.gridY) * this.gridY;
        if (x !== this.state.x || y !== this.state.y) {
            this.setState({
                x,
                y
            });
            this.props.onMove && this.props.onMove(this.state.x, this.state.y);
        }        
    }

    onMouseDown(e) {
        if (e.button !== 0) return;
        this.onStart(e);
        document.addEventListener('mousemove', this.onMouseMove);
        document.addEventListener('mouseup', this.onMouseUp);
        e.preventDefault();
    }

    onMouseUp(e) {
        document.removeEventListener('mousemove', this.onMouseMove);
        document.removeEventListener('mouseup', this.onMouseUp);
        this.props.onStop && this.props.onStop(this.state.x, this.state.y);
        e.preventDefault();
    }

    onMouseMove(e) {
        this.onMove(e);
        e.preventDefault();
    }

    onTouchStart(e) {
        this.onStart(e.touches[0]);
        document.addEventListener('touchmove', this.onTouchMove, {passive: false});
        document.addEventListener('touchend', this.onTouchEnd, {passive: false});
        e.preventDefault();
    }

    onTouchMove(e) {
        this.onMove(e.touches[0]);
        e.preventDefault();
    }

    onTouchEnd(e) {
        document.removeEventListener('touchmove', this.onTouchMove);
        document.removeEventListener('touchend', this.onTouchEnd);
        this.props.onStop && this.props.onStop(this.state.x, this.state.y);
        e.preventDefault();
    }

    render() {
        return <div
            onMouseDown={this.onMouseDown}
            onTouchStart={this.onTouchStart}
            style={{
                position: 'absolute',
                left: this.state.x,
                top: this.state.y,
                touchAction: 'none'
            }}
            ref={(div) => { this.handle = div; }}
        >
            {this.props.children}
        </div>;
    }
}

export default Draggable;

Git undo changes in some files

There are three basic ways to do this depending on what you have done with the changes to the file A. If you have not yet added the changes to the index or committed them, then you just want to use the checkout command - this will change the state of the working copy to match the repository:

git checkout A

If you added it to the index already, use reset:

git reset A

If you had committed it, then you use the revert command:

# the -n means, do not commit the revert yet
git revert -n <sha1>
# now make sure we are just going to commit the revert to A
git reset B
git commit

If on the other hand, you had committed it, but the commit involved rather a lot of files that you do not also want to revert, then the above method might involve a lot of "reset B" commands. In this case, you might like to use this method:

# revert, but do not commit yet
git revert -n <sha1>
# clean all the changes from the index
git reset
# now just add A
git add A
git commit

Another method again, requires the use of the rebase -i command. This one can be useful if you have more than one commit to edit:

# use rebase -i to cherry pick the commit you want to edit
# specify the sha1 of the commit before the one you want to edit
# you get an editor with a file and a bunch of lines starting with "pick"
# change the one(s) you want to edit to "edit" and then save the file
git rebase -i <sha1>
# now you enter a loop, for each commit you set as "edit", you get to basically redo that commit from scratch
# assume we just picked the one commit with the erroneous A commit
git reset A
git commit --amend
# go back to the start of the loop
git rebase --continue

Using IF ELSE statement based on Count to execute different Insert statements

Depending on your needs, here are a couple of ways:

IF EXISTS (SELECT * FROM TABLE WHERE COLUMN = 'SOME VALUE')
    --INSERT SOMETHING
ELSE
    --INSERT SOMETHING ELSE

Or a bit longer

DECLARE @retVal int

SELECT @retVal = COUNT(*) 
FROM TABLE
WHERE COLUMN = 'Some Value'

IF (@retVal > 0)
BEGIN
    --INSERT SOMETHING
END
ELSE
BEGIN
    --INSERT SOMETHING ELSE
END 

How do I make a column unique and index it in a Ruby on Rails migration?

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name.

String escape into XML

WARNING: Necromancing

Still Darin Dimitrov's answer + System.Security.SecurityElement.Escape(string s) isn't complete.

In XML 1.1, the simplest and safest way is to just encode EVERYTHING.
Like &#09; for \t.
It isn't supported at all in XML 1.0.
For XML 1.0, one possible workaround is to base-64 encode the text containing the character(s).

//string EncodedXml = SpecialXmlEscape("?????? ???");
//Console.WriteLine(EncodedXml);
//string DecodedXml = XmlUnescape(EncodedXml);
//Console.WriteLine(DecodedXml);
public static string SpecialXmlEscape(string input)
{
    //string content = System.Xml.XmlConvert.EncodeName("\t");
    //string content = System.Security.SecurityElement.Escape("\t");
    //string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("&#09;");
    //strDelimiter = XmlUnescape("&#59;");
    //Console.WriteLine(strDelimiter);
    //Console.WriteLine(string.Format("&#{0};", (int)';'));
    //Console.WriteLine(System.Text.Encoding.ASCII.HeaderName);
    //Console.WriteLine(System.Text.Encoding.UTF8.HeaderName);


    string strXmlText = "";

    if (string.IsNullOrEmpty(input))
        return input;


    System.Text.StringBuilder sb = new StringBuilder();

    for (int i = 0; i < input.Length; ++i)
    {
        sb.AppendFormat("&#{0};", (int)input[i]);
    }

    strXmlText = sb.ToString();
    sb.Clear();
    sb = null;

    return strXmlText;
} // End Function SpecialXmlEscape

XML 1.0:

public static string Base64Encode(string plainText)
{
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

public static string Base64Decode(string base64EncodedData)
{
    var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
    return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Move a view up only when the keyboard covers an input field

Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?

then add these methods

 func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self

And remember to call registerForKeyboardNotifications on viewInit and deregisterFromKeyboardNotifications on exit.

Edit/Update: Swift 4.2 Syntax

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

How to center a View inside of an Android Layout?

Updated answer: Constraint Layout

It seems that the trend in Android now is to use a Constraint layout. Although it is simple enough to center a view using a RelativeLayout (as other answers have shown), the ConstraintLayout is more powerful than the RelativeLayout for more complex layouts. So it is worth learning how do do now.

To center a view, just drag the handles to all four sides of the parent.

enter image description here

Spring 3 RequestMapping: Get path value

Here is how I did it. You can see how I convert the requestedURI to a filesystem path (what this SO question is about). Bonus: and also how to respond with the file.

@RequestMapping(value = "/file/{userId}/**", method = RequestMethod.GET)
public void serveFile(@PathVariable("userId") long userId, HttpServletRequest request, HttpServletResponse response) {
    assert request != null;
    assert response != null;

    // requestURL:  http://192.168.1.3:8080/file/54/documents/tutorial.pdf
    // requestURI:  /file/54/documents/tutorial.pdf
    // servletPath: /file/54/documents/tutorial.pdf
    // logger.debug("requestURL: " + request.getRequestURL());
    // logger.debug("requestURI: " + request.getRequestURI());
    // logger.debug("servletPath: " + request.getServletPath());

    String requestURI = request.getRequestURI();
    String relativePath = requestURI.replaceFirst("^/file/", "");

    Path path = Paths.get("/user_files").resolve(relativePath);
    try {
        InputStream is = new FileInputStream(path.toFile());  
        org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        logger.error("Error writing file to output stream. Path: '" + path + "', requestURI: '" + requestURI + "'");
        throw new RuntimeException("IOError writing file to output stream");
    }
}

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Get individual query parameters from Uri

In a single line of code:

string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));

iFrame onload JavaScript event

_x000D_
_x000D_
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
    this.style.backgroundColor = "red";_x000D_
    alert(this.nodeName);_x000D_
_x000D_
    console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
_x000D_
_x000D_

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

How to manually trigger click event in ReactJS?

In a functional component this principle also works, it's just a slightly different syntax and way of thinking.

const UploadsWindow = () => {
  // will hold a reference for our real input file
  let inputFile = '';

  // function to trigger our input file click
  const uploadClick = e => {
    e.preventDefault();
    inputFile.click();
    return false;
  };

  return (
    <>
      <input
        type="file"
        name="fileUpload"
        ref={input => {
          // assigns a reference so we can trigger it later
          inputFile = input;
        }}
        multiple
      />

      <a href="#" className="btn" onClick={uploadClick}>
        Add or Drag Attachments Here
      </a>
    </>
  )

}

Copying formula to the next row when inserting a new row

Make the area with your data and formulas a Table:

enter image description here

Then adding new information in the next line will copy all formulas in that table for the new line. Data validation will also be applied for the new row as it was for the whole column. This is indeed Excel being smarter with your data.

NO VBA required...