Programs & Examples On #Stochastic process

A stochastic process is a collection of related random variables, often used as a model for a quantity that varies over time or space with some degree of smoothness.

ReactJS lifecycle method inside a function Component

You can make use of create-react-class module. Official documentation

Of course you must first install it

npm install create-react-class

Here is a working example

import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')


let Clock = createReactClass({
    getInitialState:function(){
        return {date:new Date()}
    },

    render:function(){
        return (
            <h1>{this.state.date.toLocaleTimeString()}</h1>
        )
    },

    componentDidMount:function(){
        this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
    },

    componentWillUnmount:function(){
        clearInterval(this.timerId)
    }

})

ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
)

Mapping over values in a python dictionary

Due to PEP-0469 which renamed iteritems() to items() and PEP-3113 which removed Tuple parameter unpacking, in Python 3.x you should write Martijn Pieters? answer like this:

my_dictionary = dict(map(lambda item: (item[0], f(item[1])), my_dictionary.items()))

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

Javascript - Get Image height

It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.

Opening a .ipynb.txt File

go to cmd get into file directory and type jupyter notebook filename.ipynb in my case it open code editor and provide local host connection string copy that string and paste in any browser!done

How to hide .php extension in .htaccess

1) Are you sure mod_rewrite module is enabled? Check phpinfo()

2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:

/folder/thing -> /folder/thing.php

If you actually want

/thing -> /folder/thing.php

You need to drop the folder from the match expression.

I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):

RewriteRule ^([^/\.]+)/?$ $1.php  [L,QSA]

3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.

When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.

Split long commands in multiple lines through Windows batch file

Though the carret will be preferable way to do this here's one more approach using macro that constructs a command by the passed arguments:

@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "{{=setlocal enableDelayedExpansion&for %%a in (" & set "}}="::end::" ) do if "%%~a" neq "::end::" (set command=!command! %%a) else (call !command! & endlocal)"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

%{{%
    echo
    "command"
    written
    on a
    few lines
%}}%

command is easier to read without the carets but using special symbols e.g. brackets,redirection and so on will break it. So you can this for more simpler cases. Though you can still enclose parameters in double quotes

Remove Duplicates from range of cells in excel vba

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

Sub dedupe_abcd()
    Dim icol As Long

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

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

How to catch all exceptions in c# using try and catch?

I catch all the exceptions and store it in database, so errors can be corrected easily - the page, place, date etc stored

try
{     
   Cart = DB.BuyOnlineCartMasters.Where(c => c.CmpyID == LoginID && c.Active == true).FirstOrDefault();
}
catch (Exception e)
{
    ErrorReport.StoreError("CartMinifiedPartial-Company", e);  
    -- storing the error for reference
}

Storing

public static void StoreError(string ErrorPage, Exception e)
    {
        try
        {
            eDurar.Models.db_edurarEntities1 DB = new Models.db_edurarEntities1();
            eDurar.Models.ErrorTable Err = new eDurar.Models.ErrorTable();
            Err.ErrorPage = ErrorPage;
            if (e.Message != null)
            {
                Err.ErrorDetails = e.Message;
            }
            if (e.InnerException != null)
            {
                Err.InnerException = e.InnerException.Message.ToString();
            }

            Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
            DB.ErrorTables.AddObject(Err);
            DB.SaveChanges();
}

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

How to force IE to reload javascript?

If you are looking to just do this on YOUR browser (a.k.a. not forcing this on your users), then I would NOT set your code to not utilize the cache. As José said, there is a performance loss.

And I wouldn't turn off caching on IE altogether, because you lose that performance gain for every website you visit. You can tell IE to always refresh from the server for a specific site or browsing session:

  1. Open IE Developer Tools
  2. Choose Cache from the Menu
  3. Click to check "Always Refresh From Server"

Or, for the keyboard-shortcut-philes (like myself) out there..

  • F12, Alt+C, Down Arrow, Alt+R.

NOTE OF CAUTION : Having said this... Keep in mind that anytime you develop/test in a different way than the site will be viewed in production, you run the risk of getting mixed results. A good example is this caching issue. We found an issue where IE was caching our Ajax calls and not updating results from a GET method. If we HAD disabled caching in IE, we would have never seen this problem in development, and would have deployed it to production like this.

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

Access denied for user 'test'@'localhost' (using password: YES) except root user

Do not grant all privileges over all databases to a non-root user, it is not safe (and you already have "root" with that role)

GRANT <privileges> ON database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This statement creates a new user and grants selected privileges to it. I.E.:

GRANT INSERT, SELECT, DELETE, UPDATE ON database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

Take a look at the docs to see all privileges detailed

EDIT: you can look for more info with this query (log in as "root"):

select Host, User from mysql.user;

To see what happened

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How do I open a second window from the first window in WPF?

In WPF we have a couple of options by using the Show() and ShowDialog() methods.

Well, if you want to close the opened window when a new window gets open then you can use the Show() method:

Window1 win1 = new Window1();
win1.Show();
win1.Close();

ShowDialog() also opens a window, but in this case you can not close your previously opened window.

formGroup expects a FormGroup instance

I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.

<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">

This will not render the form until it is initialized.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In Visual Studio 2012 +/-, the property page for "Configuration Properties'.Linker."Command Line" contains a box labeled "Additional Options". If you're building x64, make sure that box doesn't contain /MACHINE:I386. My projects did and it generated the error in question.

What is Ruby's double-colon `::`?

Surprisingly, all 10 answers here say the same thing. The '::' is a namespace resolution operator, and yes it is true. But there is one gotcha that you have to realize about the namespace resolution operator when it comes to the constant lookup algorithm. As Matz delineates in his book, 'The Ruby Programming Language', constant lookup has multiple steps. First, it searches a constant in the lexical scope where the constant is referenced. If it does not find the constant within the lexical scope, it then searches the inheritance hierarchy. Because of this constant lookup algorithm, below we get the expected results:

module A
  module B
      PI = 3.14
      module C
        class E
          PI = 3.15
        end
        class F < E
          def get_pi
            puts PI
          end
        end
      end
  end
end
f = A::B::C::F.new
f.get_pi
> 3.14

While F inherits from E, the B module is within the lexical scope of F. Consequently, F instances will refer to the constant PI defined in the module B. Now if module B did not define PI, then F instances will refer to the PI constant defined in the superclass E.

But what if we were to use '::' rather than nesting modules? Would we get the same result? No!

By using the namespace resolution operator when defining nested modules, the nested modules and classes are no longer within the lexical scope of their outer modules. As you can see below, PI defined in A::B is not in the lexical scope of A::B::C::D and thus we get uninitialized constant when trying to refer to PI in the get_pi instance method:

module A
end

module A::B
  PI = 3.14
end

module A::B::C
  class D
    def get_pi
      puts PI
    end
  end
end
d = A::B::C::D.new
d.get_pi
NameError: uninitialized constant A::B::C::D::PI
Did you mean?  A::B::PI

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

Can't import Numpy in Python

To install it on Debian/Ubuntu:

sudo apt-get install python-numpy

Putting images with options in a dropdown list

Checkout And Run The Following Code. It will help you...

_x000D_
_x000D_
 $( function() {_x000D_
    $.widget( "custom.iconselectmenu", $.ui.selectmenu, {_x000D_
      _renderItem: function( ul, item ) {_x000D_
        var li = $( "<li>" ),_x000D_
          wrapper = $( "<div>", { text: item.label } );_x000D_
 _x000D_
        if ( item.disabled ) {_x000D_
          li.addClass( "ui-state-disabled" );_x000D_
        }_x000D_
 _x000D_
        $( "<span>", {_x000D_
          style: item.element.attr( "data-style" ),_x000D_
          "class": "ui-icon " + item.element.attr( "data-class" )_x000D_
        })_x000D_
          .appendTo( wrapper );_x000D_
 _x000D_
        return li.append( wrapper ).appendTo( ul );_x000D_
      }_x000D_
    });_x000D_
 _x000D_
    $( "#filesA" )_x000D_
      .iconselectmenu()_x000D_
      .iconselectmenu( "menuWidget" )_x000D_
        .addClass( "ui-menu-icons" );_x000D_
 _x000D_
    $( "#filesB" )_x000D_
      .iconselectmenu()_x000D_
      .iconselectmenu( "menuWidget" )_x000D_
        .addClass( "ui-menu-icons customicons" );_x000D_
 _x000D_
    $( "#people" )_x000D_
      .iconselectmenu()_x000D_
      .iconselectmenu( "menuWidget")_x000D_
        .addClass( "ui-menu-icons avatar" );_x000D_
  } );_x000D_
  </script>_x000D_
  <style>_x000D_
    h2 {_x000D_
      margin: 30px 0 0 0;_x000D_
    }_x000D_
    fieldset {_x000D_
      border: 0;_x000D_
    }_x000D_
    label
_x000D_
{_x000D_
      display: block;_x000D_
    }_x000D_
 _x000D_
    /* select with custom icons */_x000D_
    .ui-selectmenu-menu .ui-menu.customicons .ui-menu-item-wrapper {_x000D_
      padding: 0.5em 0 0.5em 3em;_x000D_
    }_x000D_
    .ui-selectmenu-menu .ui-menu.customicons .ui-menu-item .ui-icon {_x000D_
      height: 24px;_x000D_
      width: 24px;_x000D_
      top: 0.1em;_x000D_
    }_x000D_
    .ui-icon.video {_x000D_
      background: url("images/24-video-square.png") 0 0 no-repeat;_x000D_
    }_x000D_
    .ui-icon.podcast {_x000D_
      background: url("images/24-podcast-square.png") 0 0 no-repeat;_x000D_
    }_x000D_
    .ui-icon.rss {_x000D_
      background: url("images/24-rss-square.png") 0 0 no-repeat;_x000D_
    }_x000D_
 _x000D_
    /* select with CSS avatar icons */_x000D_
    option.avatar {_x000D_
      background-repeat: no-repeat !important;_x000D_
      padding-left: 20px;_x000D_
    }_x000D_
    .avatar .ui-icon {_x000D_
      background-position: left top;_x000D_
    }
_x000D_
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <title>jQuery UI Selectmenu - Custom Rendering</title>_x000D_
  _x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<div class="demo">_x000D_
 _x000D_
<form action="#">_x000D_
  <h2>Selectmenu with framework icons</h2>_x000D_
  <fieldset>_x000D_
    <label for="filesA">Select a File:</label>_x000D_
    <select name="filesA" id="filesA">_x000D_
      <option value="jquery" data-class="ui-icon-script">jQuery.js</option>_x000D_
      <option value="jquerylogo" data-class="ui-icon-image">jQuery Logo</option>_x000D_
      <option value="jqueryui" data-class="ui-icon-script">ui.jQuery.js</option>_x000D_
      <option value="jqueryuilogo" selected="selected" data-class="ui-icon-image">jQuery UI Logo</option>_x000D_
      <option value="somefile" disabled="disabled" data-class="ui-icon-help">Some unknown file</option>_x000D_
    </select>_x000D_
  </fieldset>_x000D_
 _x000D_
  <h2>Selectmenu with custom icon images</h2>_x000D_
  <fieldset>_x000D_
    <label for="filesB">Select a podcast:</label>_x000D_
    <select name="filesB" id="filesB">_x000D_
      <option value="mypodcast" data-class="podcast">John Resig Podcast</option>_x000D_
      <option value="myvideo" data-class="video">Scott González Video</option>_x000D_
      <option value="myrss" data-class="rss">jQuery RSS XML</option>_x000D_
    </select>_x000D_
  </fieldset>_x000D_
 _x000D_
  <h2>Selectmenu with custom avatar 16x16 images as CSS background</h2>_x000D_
  <fieldset>_x000D_
    <label for="people">Select a Person:</label>_x000D_
    <select name="people" id="people">_x000D_
      <option value="1" data-class="avatar" data-style="background-image: url(&apos;http://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&amp;r=g&amp;s=16&apos;);">John Resig</option>_x000D_
      <option value="2" data-class="avatar" data-style="background-image: url(&apos;http://www.gravatar.com/avatar/e42b1e5c7cfd2be0933e696e292a4d5f?d=monsterid&amp;r=g&amp;s=16&apos;);">Tauren Mills</option>_x000D_
      <option value="3" data-class="avatar" data-style="background-image: url(&apos;http://www.gravatar.com/avatar/bdeaec11dd663f26fa58ced0eb7facc8?d=monsterid&amp;r=g&amp;s=16&apos;);">Jane Doe</option>_x000D_
    </select>_x000D_
  </fieldset>_x000D_
</form>_x000D_
 _x000D_
</div>_x000D_
 _x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

Most efficient method to groupby on an array of objects

let groupbyKeys = function(arr, ...keys) {
  let keysFieldName = keys.join();
  return arr.map(ele => {
    let keysField = {};
    keysField[keysFieldName] = keys.reduce((keyValue, key) => {
      return keyValue + ele[key]
    }, "");
    return Object.assign({}, ele, keysField);
  }).reduce((groups, ele) => {
    (groups[ele[keysFieldName]] = groups[ele[keysFieldName]] || [])
      .push([ele].map(e => {
        if (keys.length > 1) {
          delete e[keysFieldName];
        }
        return e;
    })[0]);
    return groups;
  }, {});
};

console.log(groupbyKeys(array, 'Phase'));
console.log(groupbyKeys(array, 'Phase', 'Step'));
console.log(groupbyKeys(array, 'Phase', 'Step', 'Task'));

How to run TypeScript files from command line?

For environments such as Webstorm where the node command cannot be changed to ts-node or npx:

  1. npm install ts-node typescript (Install dependencies)
  2. node --require ts-node/register src/foo.ts (Add --require ts-node/register to "Node parameters")

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

If you don't have the API enabled, but have an API key, you won't get that error if you run an API from the browser (such as when displaying a map) or pass the request to the curl command. You only get that error if you call an API within code. In Python, it doesn't matter if you use urllib, pycurl, construct the curl command and pass it to subprocess.check_output(), or send the request using jQuery.get(); you still get that error. I wonder how Google knows the difference.

Listing contents of a bucket with boto3

With little modification to @Hephaeastus 's code in one of the above comments, wrote the below method to list down folders and objects (files) in a given path. Works similar to s3 ls command.

from boto3 import session

def s3_ls(profile=None, bucket_name=None, folder_path=None):
    folders=[]
    files=[]
    result=dict()
    bucket_name = bucket_name
    prefix= folder_path
    session = boto3.Session(profile_name=profile)
    s3_conn   = session.client('s3')
    s3_result =  s3_conn.list_objects_v2(Bucket=bucket_name, Delimiter = "/", Prefix=prefix)
    if 'Contents' not in s3_result and 'CommonPrefixes' not in s3_result:
        return []

    if s3_result.get('CommonPrefixes'):
        for folder in s3_result['CommonPrefixes']:
            folders.append(folder.get('Prefix'))

    if s3_result.get('Contents'):
        for key in s3_result['Contents']:
            files.append(key['Key'])

    while s3_result['IsTruncated']:
        continuation_key = s3_result['NextContinuationToken']
        s3_result = s3_conn.list_objects_v2(Bucket=bucket_name, Delimiter="/", ContinuationToken=continuation_key, Prefix=prefix)
        if s3_result.get('CommonPrefixes'):
            for folder in s3_result['CommonPrefixes']:
                folders.append(folder.get('Prefix'))
        if s3_result.get('Contents'):
            for key in s3_result['Contents']:
                files.append(key['Key'])

    if folders:
        result['folders']=sorted(folders)
    if files:
        result['files']=sorted(files)
    return result

This lists down all objects / folders in a given path. Folder_path can be left as None by default and method will list the immediate contents of the root of the bucket.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Swift 3 - Comparing Date objects

SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.

func checkTimeStamp(date: String!) -> Bool {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale(identifier:"en_US_POSIX")
        let datecomponents = dateFormatter.date(from: date)

        let now = Date()

        if (datecomponents! >= now) {
            return true
        } else {
            return false
        }
    }

To use it:

if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
    // Do something
}

How can I get a vertical scrollbar in my ListBox?

The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox 
    ItemsSource="{Binding}" 
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

Sum of values in an array using jQuery

Another method, if eval is safe & fast :

eval(["10","20","30","40","50"].join("+"))

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

Make DateTimePicker work as TimePicker only in WinForms

If you want to do it from properties, you can do this by setting the Format property of DateTimePicker to DateTimePickerFormat.Time and ShowUpDown property to true. Also, customFormat can be set in properties.

Making a div vertically scrollable using CSS

Well the above answers have give a good explanations to half of the question. For the other half.

Why don't just hide the scroll bar itself. This way it will look more appealing as most of the people ( including me ) hate the scroll bar. You can use this code

::-webkit-scrollbar {
    width: 0px;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}

.setAttribute("disabled", false); changes editable attribute to false

Using method set and remove attribute

_x000D_
_x000D_
function radioButton(o) {_x000D_
_x000D_
  var text = document.querySelector("textarea");_x000D_
_x000D_
  if (o.value == "on") {_x000D_
    text.removeAttribute("disabled", "");_x000D_
    text.setAttribute("enabled", "");_x000D_
  } else {_x000D_
    text.removeAttribute("enabled", "");_x000D_
    text.setAttribute("disabled", "");_x000D_
  }_x000D_
  _x000D_
}
_x000D_
<input type="radio" name="radioButton" value="on" onclick = "radioButton(this)" />Enable_x000D_
<input type="radio" name="radioButton" value="off" onclick = "radioButton(this)" />Disabled<hr/>_x000D_
_x000D_
<textarea disabled ></textarea>
_x000D_
_x000D_
_x000D_

how to run mysql in ubuntu through terminal

You seem to just have begun using mysql.

Simple answer: for now use

mysql -u root -p password

Password is usually root by default. You may use other usernames if you have created other user using create user in mysql. For details use "help, help manage accounts, help create users" etc. If you dont want your password to be shown in open just press return key after "-p" and you will be prompted for password next. Hope this resolves the issue.

How to change Screen buffer size in Windows Command Prompt from batch script

If anyone is still wondering, on the newer versions of windows you can use powershell:

powershell.exe -command "& {$pshost = Get-Host;$pswindow = $pshost.UI.RawUI;$newsize = $pswindow.BufferSize;$newsize.height = 150;$pswindow.buffersize = $newsize;}"

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

How can I pass an Integer class correctly by reference?

I think it is the autoboxing that is throwing you off.

This part of your code:

   public static Integer inc(Integer i) {
        i = i+1;    // I think that this must be **sneakally** creating a new integer...  
        System.out.println("Inc: "+i);
        return i;
    }

Really boils down to code that looks like:

  public static Integer inc(Integer i) {
        i = new Integer(i) + new Integer(1);      
        System.out.println("Inc: "+i);
        return i;
    }

Which of course.. will not changes the reference passed in.

You could fix it with something like this

  public static void main(String[] args) {
        Integer integer = new Integer(0);
        for (int i =0; i<10; i++){
            integer = inc(integer);
            System.out.println("main: "+integer);
        }
    }

Return content with IHttpActionResult for non-OK response

You can use this:

return Content(HttpStatusCode.BadRequest, "Any object");

How to sum the values of one column of a dataframe in spark/scala

Simply apply aggregation function, Sum on your column

df.groupby('steps').sum().show()

Follow the Documentation http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html

Check out this link also https://www.analyticsvidhya.com/blog/2016/10/spark-dataframe-and-operations/

Deserializing JSON Object Array with Json.net

Using the accepted answer you have to access each record by using Customers[i].customer, and you need an extra CustomerJson class, which is a little annoying. If you don't want to do that, you can use the following:

public class CustomerList
{
    [JsonConverter(typeof(MyListConverter))]
    public List<Customer> customer { get; set; }
}

Note that I'm using a List<>, not an Array. Now create the following class:

class MyListConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Values())
        {
            var childToken = child.Children().First();
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(childToken.CreateReader(), newObject);
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}

Maven and adding JARs to system scope

System scope was only designed to deal with 'system' files; files sitting in some fixed location. Files in /usr/lib, or ${java.home} (e.g. tools.jar). It wasn't designed to support miscellaneous .jar files in your project.

The authors intentionally refused to make the pathname expansions work right for that to discourage you. As a result, in the short term you can use install:install-file to install into the local repo, and then some day use a repo manager to share.

iPad/iPhone hover problem causes the user to double click a link

I think it'd be wise to try mouseenter in place of mouseover. It's what's used internally when binding to .hover(fn,fn) and is generally what you want.

How do you declare string constants in C?

There's one more (at least) road to Rome:

static const char HELLO3[] = "Howdy";

(static — optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*, because then you'll be able to use sizeof(HELLO3) and therefore you don't have to postpone till runtime what you can do at compile time.

The define has an advantage of compile-time concatenation, though (think HELLO ", World!") and you can sizeof(HELLO) as well.

But then you can also prefer const char* and use it across multiple files, which would save you a morsel of memory.

In short — it depends.

How to write some data to excel file(.xlsx)

Try this code

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

HTTP GET request in JavaScript?

Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.

Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

Using it is as easy as:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});

Connecting to Microsoft SQL server using Python

I found up-to-date resources here: Microsoft | SQL Docs | Python SQL Driver

There are these two options explained including all the prerequisites needed and code examples: Python SQL driver - pyodbc (tested & working) Python SQL driver - pymssql

Create WordPress Page that redirects to another URL

There is a much simpler way in wordpress to create a redirection by using wordpress plugins. So here i found a better way through the plugin Redirection and also you can find other as well on this site Create Url redirect in wordpress through Plugin

Determine path of the executing script

I liked steamer25's solution as it seems the most robust for my purposes. However, when debugging in RStudio (in windows), the path would not get set properly. The reason being that if a breakpoint is set in RStudio, sourcing the file uses an alternate "debug source" command which sets the script path a little differently. Here is the final version which I am currently using which accounts for this alternate behavior within RStudio when debugging:

# @return full path to this script
get_script_path <- function() {
    cmdArgs = commandArgs(trailingOnly = FALSE)
    needle = "--file="
    match = grep(needle, cmdArgs)
    if (length(match) > 0) {
        # Rscript
        return(normalizePath(sub(needle, "", cmdArgs[match])))
    } else {
        ls_vars = ls(sys.frames()[[1]])
        if ("fileName" %in% ls_vars) {
            # Source'd via RStudio
            return(normalizePath(sys.frames()[[1]]$fileName)) 
        } else {
            # Source'd via R console
            return(normalizePath(sys.frames()[[1]]$ofile))
        }
    }
}

Node.js: Difference between req.query[] and req.params

req.params contains route parameters (in the path portion of the URL), and req.query contains the URL query parameters (after the ? in the URL).

You can also use req.param(name) to look up a parameter in both places (as well as req.body), but this method is now deprecated.

How do I change a tab background color when using TabLayout?

What finally worked for me is similar to what @????DJ suggested, but the tabBackground should be in the layout file and not inside the style, so it looks like:

res/layout/somefile.xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

and the selector res/drawable/tab_color_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

How to use PHP OPCache?

I am going to drop in my two cents for what I use opcache.

I have made an extensive framework with a lot of fields and validation methods and enums to be able to talk to my database.

Without opcache

When using this script without opcache and I push 9000 requests in 2.8 seconds to the apache server it maxes out at 90-100% cpu for 70-80 seconds until it catches up with all the requests.

Total time taken: 76085 milliseconds(76 seconds)

With opcache enabled

With opcache enabled it runs at 25-30% cpu time for about 25 seconds and never passes 25% cpu use.

Total time taken: 26490 milliseconds(26 seconds)

I have made an opcache blacklist file to disable the caching of everything except the framework which is all static and doesnt need changing of functionality. I choose explicitly for just the framework files so that I could develop without worrying about reloading/validating the cache files. Having everything cached saves a second on the total of the requests 25546 milliseconds

This significantly expands the amount of data/requests I can handle per second without the server even breaking a sweat.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

In my case, stopping Proxifier fixed it. I added a rule to route any connections from vpnkit.exe as Direct and it now works.

How to construct a REST API that takes an array of id's for the resources

If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:

api.com/users?id=id1,id2,id3,id4,id5

How can I select checkboxes using the Selenium Java WebDriver?

To get the checkbox for 'Seaside & Country Homes', use this XPath:

//label[text()='Seaside & Country Homes']/preceding-sibling::input[@type='checkbox']

To get the checkbox for 'housingmoves', use this XPath:

//label[text()='housingmoves']/preceding-sibling::input[@type='checkbox']

The principle here is to get the label with the text you want, then get the checkbox that is before the label, since that seems to be how your HTML is laid out.

To get all checkboxes, you would start a little higher up and then work down, so that is to say get the table, and then get any checkbox within a span:

//table/descendant::span/input[@type='checkbox']

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

What is the difference between DSA and RSA?

Referring, https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html

RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

Display A Popup Only Once Per User

Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.

$scope.storage = $localStorage; //connects an object to $localstorage

$scope.storage.hasSeenPopup = "false";  // they haven't seen it


$scope.showPopup = function() {  // popup to tell people to turn sound on

    $scope.data = {}
    // An elaborate, custom popup
    var myPopup = $ionicPopup.show({
        template: '<p class="popuptext">Turn Sound On!</p>',
        cssClass: 'popup'

    });        
    $timeout(function() {
        myPopup.close(); //close the popup after 3 seconds for some reason
    }, 2000);
    $scope.storage.hasSeenPopup = "true"; // they've now seen it

};

$scope.playStream = function(show) {
    PlayerService.play(show);

    $scope.audioObject = audioObject; // this allow for styling the play/pause icons

    if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
        $scope.showPopup();
    }
}

How to get MAC address of your machine using a C program?

You want to take a look at the getifaddrs(3) manual page. There is an example in C in the manpage itself that you can use. You want to get the address with the type AF_LINK.

Android, How to create option Menu

public class MenuTest extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.more_tab_menu, menu);

        // return true so that the menu pop up is opened
        return true; 
    }
}

and don't forget to press the menu button or icon on Emulator or device

addClass and removeClass in jQuery - not removing class

I think you're almost there. The thing is, your $(this) in the "close button" listener is not the clickable div. So you want to search it first. try to replace $(this) with $(this).closest(".clickable") . And don't forget the e.stopPropagation() as Guilherme is suggesting. that should be something like:

$( document ).ready(function() {   
    $(document).on("click", ".close_button", function () { 
        alert ("oi");
        e.stopPropagation()
        $(this).closest(".clickable").addClass("spot");
        $(this).closest(".clickable").removeClass("grown");
    });  


    $(document).on("click", ".clickable", function () {
        if ($(this).hasClass("spot")){
            $(this).addClass("grown");
            $(this).removeClass("spot");
        }
    });
});

Use jQuery to change an HTML tag?

You can achieve by data-* attribute like data-replace="replaceTarget,replaceBy" so with help of jQuery to get replaceTarget & replaceBy value by .split() method after getting values then use .replaceWith() method.
This data-* attribute technique to easily manage any tag replacement without changing below (common code for all tag replacement).

I hope below snippet will help you lot.

_x000D_
_x000D_
$(document).on('click', '[data-replace]', function(){_x000D_
  var replaceTarget = $(this).attr('data-replace').split(',')[0];_x000D_
  var replaceBy = $(this).attr('data-replace').split(',')[1];_x000D_
  $(replaceTarget).replaceWith($(replaceBy).html($(replaceTarget).html()));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<p id="abc">Hello World #1</p>_x000D_
<a href="#" data-replace="#abc,<h1/>">P change with H1 tag</a>_x000D_
<hr>_x000D_
<h2 id="xyz">Hello World #2</h2>_x000D_
<a href="#" data-replace="#xyz,<p/>">H1 change with P tag</a>_x000D_
<hr>_x000D_
<b id="bold">Hello World #2</b><br>_x000D_
<a href="#" data-replace="#bold,<i/>">B change with I tag</a>_x000D_
<hr>_x000D_
<i id="italic">Hello World #2</i><br>_x000D_
<a href="#" data-replace="#italic,<b/>">I change with B tag</a>
_x000D_
_x000D_
_x000D_

Why is my xlabel cut off in my matplotlib plot?

An easy option is to configure matplotlib to automatically adjust the plot size. It works perfectly for me and I'm not sure why it's not activated by default.

Method 1

Set this in your matplotlibrc file

figure.autolayout : True

See here for more information on customizing the matplotlibrc file: http://matplotlib.org/users/customizing.html

Method 2

Update the rcParams during runtime like this

from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})

The advantage of using this approach is that your code will produce the same graphs on differently-configured machines.

JPA - Returning an auto generated id after persist()

@Entity
public class ABC implements Serializable {
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;   
}

check that @GeneratedValue notation is there in your entity class.This tells JPA about your entity property auto-generated behavior

Python: Finding differences between elements of a list

I would suggest using

v = np.diff(t)

this is simple and easy to read.

But if you want v to have the same length as t then

v = np.diff([t[0]] + t) # for python 3.x

or

v = np.diff(t + [t[-1]])

FYI: this will only work for lists.

for numpy arrays

v = np.diff(np.append(t[0], t))

Read a text file using Node.js?

I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt from a script rooms/rooms.js

var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
    data += chunk;
}).on('end', function() {
    console.log(data);
});

What is the result of % in Python?

Modulus - Divides left hand operand by right hand operand and returns remainder.

If it helps:

1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true

... and so on.

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

How do I count occurrence of duplicate items in array

this code will return duplicate value in same array

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
  if(array_count_values($arr)[$item] > 1){
     echo "Found Matched value : ".$item." <br />";
  }
}

Reading all files in a directory, store them in objects, and send the object

For the code to work smoothy in different enviroments, path.resolve can be used in places where path is manipulated. Here is code which works better.

Reading part:

var fs = require('fs');

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}

Storing part:

var data = {};
readFiles(path.resolve(__dirname, 'dirname/'), function(filename, content) {
  data[filename] = content;
}, function(error) {
  throw err;
});

Javascript array sort and unique

function sort() only is only good if your number has same digit, example:

var myData = ["3","11","1","2"]

will return;

var myData = ["1","11","2","3"]

and here improvement for function from mrmonkington

myData.sort().sort(function(a,b){return a - b;}).filter(function(el,i,a){if(i==a.indexOf(el) & el.length>0)return 1;return 0;})

the above function will also delete empty array and you can checkout the demo below

http://jsbin.com/ahojip/2/edit

Common sources of unterminated string literal

Try a "binary search". Delete half the code and try again. If the error is still there, delete half the remaining code. If the error is not there, put what you deleted back in, and delete half of that. Repeat.

You should be able to narrow it down to a few line fairly quickly. My experience has been that at this point, you will notice some stupid malformed string.

It may be expedient to perform this on a saved version of the HTML output to the browser, if you're not sure which server-side resource the error is in.

Return index of highest value in an array

My solution to get the higher key is as follows:

max(array_keys($values['Users']));

Which header file do you include to use bool type in c in linux?

Try this header file in your code

stdbool.h

This must work

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

C# Switch-case string starting with

If the problem domain has some kind of string header concept, this could be modelled as an enum.

switch(GetStringHeader(s))
{
    case StringHeader.ABC: ...
    case StringHeader.QWERTY: ...
    ...
}

StringHeader GetStringHeader(string s)
{
    if (s.StartsWith("ABC")) return StringHeader.ABC;
    ...
}

enum StringHeader { ABC, QWERTY, ... }

Loading a .json file into c# program

Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class RootObject
{
    public string url_short { get; set; }
    public string url_long { get; set; }
    public int type { get; set; }
}

public class Program
{
    static public void Main()
    {
       using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
       {
           string json = r.ReadToEnd();
           List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
       }

    Console.WriteLine(ro[0].url_short);                 
    }  
}

Note : Look below link also I have answered for question similar to this.It will be help full for you How to Parse an example string in C#

Download a single folder or directory from a GitHub repo

You can try using the gitzip extension for chrome, its super easy to use and has helped me download many folders before too!

Service Reference Error: Failed to generate code for the service reference

Have to uncheck the Reuse types in all referenced assemblies from Configure service reference option

Check this for details

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

Can't import database through phpmyadmin file size too large

You no need to edit php.ini or any thing. I suggest best thing as Just use MySQL WorkBench.

JUST FOLLOW THE STEPS.

Install MySQL WorkBench 6.0

And In "Navigation panel"(Left side) there is option call 'Data import' under "MANAGEMENT". Click that and [follow steps below]

  1. click Import Self-Contained File and choose your SQL file
  2. Go to My Document and create folder call "dump"[simple].
  3. now you ready to upload file. Click IMPORT Button on down.

Java JDBC connection status

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

How can I add new item to the String array?

String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

To show only file name without the entire directory path

When you want to list names in a path but they have different file extensions.

me@server:/var/backups$ ls -1 *.zip && ls -1 *.gz

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:

ng update @angular/core @angular/cli

That will update your local angular version to 9. Then, just to sync material, run: ng update @angular/material

Android: How to turn screen on and off programmatically?

Regarding to Android documentation it can be achieve by using following code line:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

I have added this in my onCreate method and it works fine.

On the link you will find different ways to achieve this and general explanation as well.

Link to the documenation: https://developer.android.com/training/scheduling/wakelock.html

What is the difference between String and StringBuffer in Java?

A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.

You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.

AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.

How to combine two byte arrays

The simplest method (inline, assuming a and b are two given arrays):

byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);

This, of course, works with more than two summands and uses a concatenation charset, defined somewhere in your code:

static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;

Or, in more simple form, without this charset:

byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");

But you need to suppress UnsupportedEncodingException which is unlikely to be thrown.


The fastest method:

public static byte[] concat(byte[] a, byte[] b) {
    int lenA = a.length;
    int lenB = b.length;
    byte[] c = Arrays.copyOf(a, lenA + lenB);
    System.arraycopy(b, 0, c, lenA, lenB);
    return c;
}

How do I implement __getattribute__ without an infinite recursion error?

Python language reference:

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Meaning:

def __getattribute__(self,name):
    ...
        return self.__dict__[name]

You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

return  object.__getattribute__(self, name)

Using the base classes __getattribute__ helps finding the real attribute.

How to abort makefile if variable not set?

For simplicity and brevity:

$ cat Makefile
check-%:
        @: $(if $(value $*),,$(error $* is undefined))

bar:| check-foo
        echo "foo is $$foo"

With outputs:

$ make bar
Makefile:2: *** foo is undefined. Stop.
$ make bar foo="something"
echo "foo is $$foo"
foo is something

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

Use find command but exclude files in two directories

Here's how you can specify that with find:

find . -type f -name "*_peaks.bed" ! -path "./tmp/*" ! -path "./scripts/*"

Explanation:

  • find . - Start find from current working directory (recursively by default)
  • -type f - Specify to find that you only want files in the results
  • -name "*_peaks.bed" - Look for files with the name ending in _peaks.bed
  • ! -path "./tmp/*" - Exclude all results whose path starts with ./tmp/
  • ! -path "./scripts/*" - Also exclude all results whose path starts with ./scripts/

Testing the Solution:

$ mkdir a b c d e
$ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
$ find . -type f ! -path "./a/*" ! -path "./b/*"

./d/4
./c/3
./e/a
./e/b
./e/5

You were pretty close, the -name option only considers the basename, where as -path considers the entire path =)

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

Correct MySQL configuration for Ruby on Rails Database.yml file

If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work

$ cat config/database.yml
 
$ echo $DATABASE_URL
mysql://root:[email protected]:3306/my_db_name

for Heroku: heroku config:set DATABASE_URL='mysql://root:[email protected]/my_db_name'

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you not use maven, try to put your jars to WEB-INF/lib, it worked for me.

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

What is the Regular Expression For "Not Whitespace and Not a hyphen"

[^\s-]

should work and so will

[^-\s]
  • [] : The char class
  • ^ : Inside the char class ^ is the negator when it appears in the beginning.
  • \s : short for a white space
  • - : a literal hyphen. A hyphen is a meta char inside a char class but not when it appears in the beginning or at the end.

align 3 images in same row with equal spaces?

I assumed the first DIV is #content :

<div id="content">
   <img src="@Url.Content("~/images/image1.bmp")" alt="" />
   <img src="@Url.Content("~/images/image2.bmp")" alt="" />
   <img src="@Url.Content("~/images/image3.bmp")" alt="" />
</div>

And CSS :

#content{
         width: 700px;
         display: block;
         height: auto;
     }
     #content > img{
        float: left; width: 200px;
        height: 200px;
        margin: 5px 8px;
     }

encapsulation vs abstraction real world example

I feel like encapsulation may make more sense to discuss when you see HOW NOT TO DO in programming. For example, consider a Car class as below.

 class Car{
   public float speed =0;
   public boolean isReverse = false;
   public boolean isStarted = false;
 }

The client code may use above car class as below.

class Main{
  public static void main(args String[]){
   Car car = new Car();
   // No need to start??
   car.speed = 100; // Turbo mode directly to 100
   car.speed = 0; // Turbo break
  }
}

See more at: http://brevitaz.com/encapsulation-example-benefits-java/

This is uncontrolled access to car speed and other variables. By encapsulation, Car class can have complete control over how the data variables within car class can be modified.

Any concrete entity that has some behavior is example of Encapsulation. The behavior is provided by wrapping up something and hiding something from client.In case of mobile, it is signals, chips, circuits, battery and so on.

For abstraction of the same example - normal user may say I am ok with anything using which I can make calls and receive calls. This abstraction can be substituted by any concrete mobile. Check out Abstraction examples.

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Please Try This for Getting column Index

Private Sub lvDetail_MouseMove(sender As Object, e As MouseEventArgs) Handles lvDetail.MouseClick

    Dim info As ListViewHitTestInfo = lvDetail.HitTest(e.X, e.Y)
    Dim rowIndex As Integer = lvDetail.FocusedItem.Index
    lvDetail.Items(rowIndex).Selected = True
    Dim xTxt = info.SubItem.Text
    For i = 0 To lvDetail.Columns.Count - 1
        If lvDetail.SelectedItems(0).SubItems(i).Text = xTxt Then
            MsgBox(i)
        End If
    Next
End Sub

What's the main difference between int.Parse() and Convert.ToInt32

No difference as such.
Convert.ToInt32() calls int.Parse() internally

Except for one thing Convert.ToInt32() returns 0 when argument is null

Otherwise both work the same way

How do I clear/delete the current line in terminal?

In order to clean the whole line (2 different ways):

  • Home , Ctrl+K
  • End , Ctrl+U

undefined reference to boost::system::system_category() when compiling

Linking with a library that defines the missing symbol (-lboost_system) is the obvious solution, but in the particular case of Boost.System, a misfeature in the original design makes it use boost::system::generic_category() and boost::system::system_category() needlessly. Compiling with the flag -DBOOST_SYSTEM_NO_DEPRECATED disables that code and lets a number of programs compile without requiring -lboost_system (that link is of course still needed if you explicitly use some of the library's features).

Starting from Boost 1.66 and this commit, this behavior is now the default, so hopefully fewer and fewer users should need this answer.

As noticed by @AndrewMarshall, an alternative is to define BOOST_ERROR_CODE_HEADER_ONLY which enables a header-only version of the code. This was discouraged by Boost as it can break some functionality. However, since 1.69, header-only seems to have become the default, supposedly making this question obsolete.

Viewing my IIS hosted site on other machines on my network

As others said your Firewall needs to be configured to accept incoming calls on TCP Port 80.

in win 7+ (easy wizardry way)

  1. go to windows firewall with advance security
  2. Inbound Rules -> Action -> New Rule
  3. select Predefined radio button and then select the last item - World Wide Web Services(HTTP)
  4. click next and leave the next steps as they are (allow the connection)

  • Because outbound traffic(from server to outside world) is allowed by default .it means for example http responses that web server is sending back to outside users and requests

  • But inbound traffic (originating from outside world to the server) is blocked by default like the user web requests originating from their browser which cannot reach the web server by default and you must open it.

You can also take a closer look at inbound and outbound rules at this page

How to hide element label by element id in CSS?

Despite other answers here, you should not use display:none to hide the label element.

The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).

label[for="foo"] { 
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.

How to upgrade rubygems

I found other answers to be inaccurate/outdated. Best is to refer to the actual documentation.

Short version: in most cases gem update --system will suffice.

You should not blindly use sudo. In fact if you're not required to do so you most likely should not use it.

How to start and stop android service from a adb shell?

I'm a beginner in Android, but got it working like this:

in AndroidManifest.xml, make sure you, inside <application>, have something like this:

<service android:name="com.some.package.name.YourServiceSubClassName" android:permission="com.some.package.name.YourServiceSubClassName">
    <intent-filter>
        <action android:name="com.some.package.name.YourServiceSubClassName"/>
    </intent-filter>
</service>

where YourServiceSubClassName extend android.app.Service is your java class that is the service. Where com.some.package is the package name, for me both in AndroidManifest.xml and in Java. Used a javabeat.net article as help, look for <service>

Note also, supposedly between the package name and the class name there should be .service. in the text, I guess this is some convention, but for me this caused ClassNotFoundException that I'm yet to solve.

Then, install your apk. I did from eclipse but also adb install -r yourApkHere.apk should work. Uninstall is adb uninstall com.some.package.name, btw.

You can start it from host system like this, thanks Just a Tim and MrRoy:

adb shell am startservice com.some.package.name/.YourServiceSubClassName

interestingly, I didn't need -n.

To stop, I use

adb shell am force-stop com.some.package.name

Hope it helps.

As I'm a beginner, please feel freet to edit/comment to fix any misconceptions (eg. probably regarding .service. in the component (?) name).

ImportError: No module named BeautifulSoup

you can import bs4 instead of BeautifulSoup. Since bs4 is a built-in module, no additional installation is required.

from bs4 import BeautifulSoup
import re

doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
       '</html>']
soup = BeautifulSoup(''.join(doc))

print soup.prettify()

If you want to request, using requests module. request is using urllib, requests modules. but I personally recommendation using requests module instead of urllib

module install for using:

$ pip install requests

Here's how to use the requests module:

import requests as rq
res = rq.get('http://www.example.com')

print(res.content)
print(res.status_code)

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

EDIT: If this is happening on mint/ubuntu, it is likely because you installed vscode through the software manager. This will cause other problems during debugging. Instead install it using the .deb file on the vscode website.

If you really want to use the software manager, the solution below still works:

use find / -name code 2> /dev/null to find the path to the visual studio bin file. It should end in /extra/vscode/bin/code

If you're using the mint software manager, you might only find paths with a ridiculously long name in the middle like this:

".../stable/7a22830d9e8fbbdc9627e43e072005eef66c14d2a4dd19992427ef4de060186a/..."

Just replace the long part with "/active/"

Once you have it, create a sym link:

ln -s path_you_found/extra/vscode/bin/code /usr/local/bin/code

If you don't have the rights, or only want it to be accessible for yourself, simply add this line to your .bashrc / .zshrc:

export PATH="$PATH:path_you_found/extra/vscode/bin/

Note that I removed the 'code' filename at the end

C# switch on type

I have used this form of switch-case on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.

If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.

Here is a little example expanding on Mark's solution. I think it is a great way to work with types:

Dictionary<Type, Action> typeTests;

public ClassCtor()
{
    typeTests = new Dictionary<Type, Action> ();

    typeTests[typeof(int)] = () => DoIntegerStuff();
    typeTests[typeof(string)] = () => DoStringStuff();
    typeTests[typeof(bool)] = () => DoBooleanStuff();
}

private void DoBooleanStuff()
{
   //do stuff
}

private void DoStringStuff()
{
    //do stuff
}

private void DoIntegerStuff()
{
    //do stuff
}

public Action CheckTypeAction(Type TypeToTest)
{
    if (typeTests.Keys.Contains(TypeToTest))
        return typeTests[TypeToTest];

    return null; // or some other Action delegate
}

List all environment variables from the command line

Don't lose time. Search for it in the registry:

reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

returns less than the SET command.

What is the maximum length of a table name in Oracle?

In Oracle 12.1 and below: 30 char (bytes, really, as has been stated).

But do not trust me; try this for yourself:

SQL> create table I23456789012345678901234567890 (my_id number);

Table created.



SQL> create table I234567890123456789012345678901(my_id number);


ERROR at line 1:

ORA-00972: identifier is too long

Updated: as stated above, in Oracle 12.2 and later, the maximum object name length is now 128 bytes.

Are types like uint32, int32, uint64, int64 defined in any stdlib header?

The questioner actually asked about int16 (etc) rather than (ugly) int16_t (etc).

There are no standard headers - nor any in Linux's /usr/include/ folder that define them without the "_t".

How to Maximize a firefox browser window using Selenium WebDriver with node.js

First instantiate a firefox driver

WebDriver driver = new FirefoxDriver();

then maximize it

 driver.manage().window().maximize();

Static variable inside of a function in C

6 and 7 Because static variable intialise only once, So 5++ becomes 6 at 1st call 6++ becomes 7 at 2nd call Note-when 2nd call occurs it takes x value is 6 instead of 5 because x is static variable.

How do I convert a decimal to an int in C#?

decimal d = 2;
int i = (int) d;

This should work just fine.

How to track down a "double free or corruption" error

I know this is a very old thread, but it is the top google search for this error, and none of the responses mention a common cause of the error.

Which is closing a file you've already closed.

If you're not paying attention and have two different functions close the same file, then the second one will generate this error.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

Parsing domain from a URL

I'm adding this answer late since this is the answer that pops up most on Google...

You can use PHP to...

$url = "www.google.co.uk";
$host = parse_url($url, PHP_URL_HOST);
// $host == "www.google.co.uk"

to grab the host but not the private domain to which the host refers. (Example www.google.co.uk is the host, but google.co.uk is the private domain)

To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/

The below code works when an array of public suffixes has been created already. Simply call

$domain = get_private_domain("www.google.co.uk");

with the remaining code...

// find some way to parse the above list of public suffix
// then add them to a PHP array
$suffix = [... all valid public suffix ...];

function get_public_suffix($host) {
  $parts = split("\.", $host);
  while (count($parts) > 0) {
    if (is_public_suffix(join(".", $parts)))
      return join(".", $parts);

    array_shift($parts);
  }

  return false;
}

function is_public_suffix($host) {
  global $suffix;
  return isset($suffix[$host]);
}

function get_private_domain($host) {
  $public = get_public_suffix($host);
  $public_parts = split("\.", $public);
  $all_parts = split("\.", $host);

  $private = [];

  for ($x = 0; $x < count($public_parts); ++$x) 
    $private[] = array_pop($all_parts);

  if (count($all_parts) > 0)
    $private[] = array_pop($all_parts);

  return join(".", array_reverse($private));
}

PHP - count specific array values

Use the array_count_values function.

$countValues = array_count_values($myArray);

echo $countValues["Ben"];

What are sessions? How do they work?

Simple Explanation by analogy

Imagine you are in a bank, trying to get some money out of your account. But it's dark; the bank is pitch black: there's no light and you can't see your hand in front of your face. You are surrounded by another 20 people. They all look the same. And everybody has the same voice. And everyone is a potential bad guy. In other words, HTTP is stateless.

This bank is a funny type of bank - for the sake of argument here's how things work:

  1. you wait in line (or on-line) and you talk to the teller: you make a request to withdraw money, and then
  2. you have to wait briefly on the sofa, and 20 minutes later
  3. you have to go and actually collect your money from the teller.

But how will the teller tell you apart from everyone else?

The teller can't see or readily recognise you, remember, because the lights are all out. What if your teller gives your $10,000 withdrawal to someone else - the wrong person?! It's absolutely vital that the teller can recognise you as the one who made the withdrawal, so that you can get the money (or resource) that you asked for.

Solution:

When you first appear to the teller, he or she tells you something in secret:

"When ever you are talking to me," says the teller, "you should first identify yourlself as GNASHEU329 - that way I know it's you".

Nobody else knows the secret passcode.

Example of How I Withdrew Cash:

So I decide to go to and chill out for 20 minutes and then later i go to the teller and say "I'd like to collect my withdrawal"

The teller asks me: "who are you??!"

"It's me, Mr George Banks!"

"Prove it!"

And then I tell them my passcode: GNASHEU329

"Certainly Mr Banks!"

That basically is how a session works. It allows one to be uniquely identified in a sea of millions of people. You need to identify yourself every time you deal with the teller.

If you got any questions or are unclear - please post comment and i will try to clear it up for you. The following is not strictly speaking, completely accurate in its terminology, but I hope it's helpful to you in understanding concepts.

Explanation via Pictures:

Sessions explained via Picture

Is the ternary operator faster than an "if" condition in Java

It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.

In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.

Detect if Android device has Internet connection

You don't necessarily need to make a full HTTP connection. You could try just opening a TCP connection to a known host and if it succeeds you have internet connectivity.

public boolean hostAvailable(String host, int port) {
  try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress(host, port), 2000);
    return true;
  } catch (IOException e) {
    // Either we have a timeout or unreachable host or failed DNS lookup
    System.out.println(e);
    return false;
  }
}

Then just check with:

boolean online = hostAvailable("www.google.com", 80);

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

Error source:

ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.Name);
ApplicationDbContext db = new ApplicationDbContent();
db.Users.Uploads.Add(new MyUpload{FileName="newfile.png"});
await db.SavechangesAsync();/ZZZZZZZ

Hope someone saves some precious time

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

System.Runtime.InteropServices.COMException (0x800A03EC)

It 'a permission problem when IIS is running I had this problem and I solved it in this way

I went on folders

C:\Windows\ System32\config\SystemProfile

and

C:\Windows\SysWOW64\config\SystemProfile

are protected system folders, they usually have the lock.

Right-click-> Card security-> Click on Edit-> Add untente "Autenticadet User" and assign permissions.

At this point everything is solved, if you still have problems try to give all permissions to "Everyone"

How to call a Parent Class's method from Child Class in Python?

Python 3 has a different and simpler syntax for calling parent method.

If Foo class inherits from Bar, then from Bar.__init__ can be invoked from Foo via super().__init__():

class Foo(Bar):

    def __init__(self, *args, **kwargs):
        # invoke Bar.__init__
        super().__init__(*args, **kwargs)

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I had this problem with my datasource in WildFly and Tomcat, connecting to a Oracle 10g.

I found that under certain conditions the statement wasn't closed even when the statement.close() was invoked. The problem was with the Oracle Driver we were using: ojdbc7.jar. This driver is intended for Oracle 12c and 11g, and it seems has some issues when is used with Oracle 10g, so I downgrade to ojdbc5.jar and now everything is running fine.

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

Returning Arrays in Java

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {
    {1,2,3};
}

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){
    int[] result = numbers();
    for (int i=0; i<result.length; i++) {
        System.out.print(result[i]+" ");
    }
}

Using a PHP variable in a text input value = statement

From the HTML point of view everything's been said, but to correct the PHP-side approach a little and taking thirtydot's and icktoofay's advice into account:

<?php echo '<input type="text" name="idtest" value="' . htmlspecialchars($idtest) . '">'; ?>

changing the language of error message in required field in html5 contact form

your forget this in oninvalid, change your code with this:

    oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')"

enter image description here

_x000D_
_x000D_
<form><input type="text" name="company_name"  oninvalid="this.setCustomValidity('Lütfen isaretli yerleri doldurunuz')" required /><input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Does C# have an equivalent to JavaScript's encodeURIComponent()?

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

You can add a reference to the System.Web assembly if it's not available in your project

Draw a line in a div

No need for css, you can just use the HR tag from HTML

<hr />

How to automatically import data from uploaded CSV or XLS file into Google Sheets

In case anyone would be searching - I created utility for automated import of xlsx files into google spreadsheet: xls2sheets. One can do it automatically via setting up the cronjob for ./cmd/sheets-refresh, readme describes it all. Hope that would be of use.

Properly Handling Errors in VBA (Excel)

Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume statement to clear the Error Handler. The Resume also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.

Block 3 fails because there is no Resume statement so any attempt at error handling after that will fail.

Every error handler must be ended by exiting the procedure or a Resume statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.

But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.

Sub InLineErrorHandling()

    'code without error handling

BeginTry1:

    'activate inline error handler
    On Error GoTo ErrHandler1

        'code block that may result in an error
        Dim a As String: a = "Abc"
        Dim c As Integer: c = a 'type mismatch

ErrHandler1:

    'handle the error
    If Err.Number <> 0 Then

        'the error handler has deactivated the previous error handler

        MsgBox (Err.Description)

        'Resume (or exit procedure) is the only way to get out of an error handling block
        'otherwise the following On Error statements will have no effect
        'CAUTION: it also reactivates the previous error handler
        Resume EndTry1
    End If

EndTry1:
    'CAUTION: since the Resume statement reactivates the previous error handler
    'you must ALWAYS use an On Error GoTo statement here
    'because another error here would cause an endless loop
    'use On Error GoTo 0 or On Error GoTo <Label>
    On Error GoTo 0

    'more code with or without error handling

End Sub

Sources:

The key to making this work is to use a Resume statement immediately followed by another On Error statement. The Resume is within the error handler and diverts code to the EndTry1 label. You must immediately set another On Error statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.

To avoid using the previous error handler again you need to set On Error to a new error handler or simply use On Error Goto 0 to cancel all error handling.

Close application and launch home screen on Android

Short answer: call moveTaskToBack(true) on your Activity instead of System.exit(). This will hide your application until the user wants to use it again.

The longer answer starts with another question: why do you want to kill your application?

The Android OS handles memory management and processes and so on so my advice is just let Android worry about this for you. If the user wants to leave your application they can press the Home button and your application will effectively disappear. If the phone needs more memory later the OS will terminate your application then.

As long as you're responding to lifecycle events appropriately, neither you nor the user needs to care if your application is still running or not.

So if you want to hide your application call moveTaskToBack() and let Android decide when to kill it.

C# - Substring: index and length must refer to a location within the string

The second parameter in Substring is the length of the substring, not the end index.

You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.

Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:

var prefix = "www.example.com/";
var suffix = ".jpg";
string url = "www.example.com/aaa/bbb.jpg";

if (url.StartsWith(prefix) && url.EndsWith(suffix) && url.Length >= (prefix.Length + suffix.Length))
{
    string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length);
    Console.WriteLine(newString);
}
else
    //handle invalid state

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

Set drawable size programmatically

The setBounds() method doesn't work for every type of container (did work for some of my ImageView's, however).

Try the method below to scale the drawable itself:

// Read your drawable from somewhere
Drawable dr = getResources().getDrawable(R.drawable.somedrawable);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
// Scale it to 50 x 50
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true));
// Set your new, scaled drawable "d"

Resource u'tokenizers/punkt/english.pickle' not found

The same thing happened to me recently, you just need to download the "punkt" package and it should work.

When you execute "list" (l) after having "downloaded all the available things", is everything marked like the following line?:

[*] punkt............... Punkt Tokenizer Models

If you see this line with the star, it means you have it, and nltk should be able to load it.

Concept behind putting wait(),notify() methods in Object class

I am just having hard time to understand concept behind putting wait() in object class For this questions sake consider as if wait() and notifyAll() are in thread class

In the Java language, you wait() on a particular instance of an Object – a monitor assigned to that object to be precise. If you want to send a signal to one thread that is waiting on that specific object instance then you call notify() on that object. If you want to send a signal to all threads that are waiting on that object instance, you use notifyAll() on that object.

If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify() it would have to somehow find out that thread2 was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.

In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.

In Java, we then use objects as synchronization, mutex, and communication points between threads. We synchronize on an object to get mutex access to an important code block and to synchronize memory. We wait on an object if we are waiting for some condition to change – some resource to become available. We notify on an object if we want to awaken sleeping threads.

// locks should be final objects so the object instance we are synchronizing on,
// never changes
private final Object lock = new Object();
...
// ensure that the thread has a mutex lock on some key code
synchronized (lock) {
    ...
    // i need to wait for other threads to finish with some resource
    // this releases the lock and waits on the associated monitor
    lock.wait();
    ...
    // i need to signal another thread that some state has changed and they can
    // awake and continue to run
    lock.notify();
}

There can be any number of lock objects in your program – each locking a particular resource or code segment. You might have 100 lock objects and only 4 threads. As the threads run the various parts of the program, they get exclusive access to one of the lock objects. Again, they don't have to know the running status of the other threads.

This allows you to scale up or down the number of threads running in your software as much as you want. You find that the 4 threads is blocking too much on outside resources, then you can increase the number. Pushing your battered server too hard then reduce the number of running threads. The lock objects ensure mutex and communication between the threads independent of how many threads are running.

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Another reason to go with the short one is that it matches other instances where you might specify a character set in markup. For example:

<script type="javascript" charset="UTF-8" src="/script.js"></script>

<p><a charset="UTF-8" href="http://example.com/">Example Site</a></p>

Consistency helps to reduce errors and make code more readable.

Note that the charset attribute is case-insensitive. You can use UTF-8 or utf-8, however UTF-8 is clearer, more readable, more accurate.

Also, there is absolutely no reason at all to use any value other than UTF-8 in the meta charset attribute or page header. UTF-8 is the default encoding for Web documents since HTML4 in 1999 and the only practical way to make modern Web pages.

Also you should not use HTML entities in UTF-8. Characters like the copyright symbol should be typed directly. The only entities you should use are for the 5 reserved markup characters: less than, greater than, ampersand, prime, double prime. Entities need an HTML parser, which you may not always want to use going forward, they introduce errors, make your code less readable, increase your file sizes, and sometimes decode incorrectly in various browsers depending on which entities you used. Learn how to type/insert copyright, trademark, open quote, close quote, apostrophe, em dash, en dash, bullet, Euro, and any other characters you encounter in your content, and use those actual characters in your code. The Mac has a Character Viewer that you can turn on in the Keyboard System Preference, and you can find and then drag and drop the characters you need, or use the matching Keyboard Viewer to see which keys to type. For example, trademark is Option+2. UTF-8 contains all of the characters and symbols from every written human language. So there is no excuse for using -- instead of an em dash. It is not a bad idea to learn the rules of punctuation and typography also ... for example, knowing that a period goes inside a close quote, not outside.

Using a tag for something like content-type and encoding is highly ironic, since without knowing those things, you couldn't parse the file to get the value of the meta tag.

No, that is not true. The browser starts out parsing the file as the browser's default encoding, either UTF-8 or ISO-8859-1. Since US-ASCII is a subset of both ISO-8859-1 and UTF-8, the browser can read just fine either way ... it is the same. When the browser encounters the meta charset tag, if the encoding is different than what the browser is already using, the browser reloads the page in the specified encoding. That is why we put the meta charset tag at the top, right after the head tag, before anything else, even the title. That way you can use UTF-8 characters in your title.

You must save your file(s) in UTF-8 encoding without BOM

That is not strictly true. If you only have US-ASCII characters in your document, you can Save it as US-ASCII and serve it as UTF-8, because it is a subset. But if there are Unicode characters, you are correct, you must Save as UTF-8 without BOM.

If you want a good text editor that will save your files in UTF-8, I recommend Notepad++.

On the Mac, use Bare Bones TextWrangler (free) from Mac App Store, or Bare Bones BBEdit which is at Mac App Store for $39.99 ... very cheap for such a great tool. In either app, there is a menu at the bottom of the document window where you specify the document encoding and you can easily choose "UTF-8 no BOM". And of course you can set that as the default for new documents in Preferences.

But if your Webserver serves the encoding in the HTTP header, which is recommended, both [meta tags] are needless.

That is incorrect. You should of course set the encoding in the HTTP header, but you should also set it in the meta charset attribute so that the page can be Saved by the user, out of the browser onto local storage and then Opened again later, in which case the only indication of the encoding that will be present is the meta charset attribute. You should also set a base tag for the same reason ... on the server, the base tag is unnecessary, but when opened from local storage, the base tag enables the page to work as if it is on the server, with all the assets in place and so on, no broken links.

AddDefaultCharset UTF-8

Or you can just change the encoding of particular file types like so:

AddType text/html;charset=utf-8 html

A tip for serving both UTF-8 and Latin-1 (ISO-8859-1) files is to give the UTF-8 files a "text" extension and Latin-1 files "txt."

AddType text/plain;charset=iso-8859-1 txt
AddType text/plain;charset=utf-8 text

Finally, consider Saving your documents with Unix line endings, not legacy DOS or (classic) Mac line endings, which don't help and may hurt, especially down the line as we get further and further from those legacy systems. An HTML document with valid HTML5, UTF-8 encoding, and Unix line endings is a job well done. You can share and edit and store and read and recover and rely on that document in many contexts. It's lingua franca. It's digital paper.

How to access Spring MVC model object in javascript file?

   @RequestMapping("/op")
   public ModelAndView method(Map<String, Object> model) {
       model.put("att", "helloooo");
       return new ModelAndView("dom/op");
   }

In your .js

<script>
    var valVar = [[${att}]];
</script>

What is the runtime performance cost of a Docker container?

Docker isn't virtualization, as such -- instead, it's an abstraction on top of the kernel's support for different process namespaces, device namespaces, etc.; one namespace isn't inherently more expensive or inefficient than another, so what actually makes Docker have a performance impact is a matter of what's actually in those namespaces.


Docker's choices in terms of how it configures namespaces for its containers have costs, but those costs are all directly associated with benefits -- you can give them up, but in doing so you also give up the associated benefit:

  • Layered filesystems are expensive -- exactly what the costs are vary with each one (and Docker supports multiple backends), and with your usage patterns (merging multiple large directories, or merging a very deep set of filesystems will be particularly expensive), but they're not free. On the other hand, a great deal of Docker's functionality -- being able to build guests off other guests in a copy-on-write manner, and getting the storage advantages implicit in same -- ride on paying this cost.
  • DNAT gets expensive at scale -- but gives you the benefit of being able to configure your guest's networking independently of your host's and have a convenient interface for forwarding only the ports you want between them. You can replace this with a bridge to a physical interface, but again, lose the benefit.
  • Being able to run each software stack with its dependencies installed in the most convenient manner -- independent of the host's distro, libc, and other library versions -- is a great benefit, but needing to load shared libraries more than once (when their versions differ) has the cost you'd expect.

And so forth. How much these costs actually impact you in your environment -- with your network access patterns, your memory constraints, etc -- is an item for which it's difficult to provide a generic answer.

To add server using sp_addlinkedserver

I got it. It worked fine

Thank you for your help:

EXEC sp_addlinkedserver @server='Servername'

EXEC sp_addlinkedsrvlogin 'Servername', 'false', NULL, 'username', 'password@123'

How to print the values of slices

You could use a for loop to print the []Project as shown in @VonC excellent answer.

package main

import "fmt"

type Project struct{ name string }

func main() {
    projects := []Project{{"p1"}, {"p2"}}
    for i := range projects {
        p := projects[i]
        fmt.Println(p.name) //p1, p2
    }
}

css background image in a different folder from css

I had a similar problem but solved changing the direction of the slash sign: For some reason when Atom copies Paths from the project folder it does so like background-image: url(img\image.jpg\)instead of (img/image.jpeg)

While i can see it's not the case for OP may be useful for other people (I just wasted half the morning wondering why my stylesheet wasn´t loading)

How do I create a file AND any folders, if the folders don't exist?

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

Obtain form input fields using jQuery?

serialize() is the best method. @ Christopher Parker say that Nickf's anwser accomplishes more, however it does not take into account that the form may contain textarea and select menus. It is far better to use serialize() and then manipulate that as you need to. Data from serialize() can be used in either an Ajax post or get, so there is no issue there.

Cannot find or open the PDB file in Visual Studio C++ 2010

Answer by Paul is right, I am just putting the visual to easily get there.

Go to Tools->Options->Debugging->Symbols

Set the checkbox marked in red and it will download the pdb files from microsoft. When you set the checkbox, it will also set a default path for the pdb files in the edit box under, you don't need to change that.

enter image description here

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

VBA paste range

I would try

Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy

Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste

React PropTypes : Allow different types of PropTypes for one prop

size: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

Learn more: Typechecking With PropTypes

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

endsWith in JavaScript

  1. Unfortunately not.
  2. if( "mystring#".substr(-1) === "#" ) {}

Font-awesome, input type 'submit'

You can use button classes btn-link and btn-xs with type submit, which will make a small invisible button with an icon inside of it. Example:

<button class="btn btn-link btn-xs" type="submit" name="action" value="delete">
    <i class="fa fa-times text-danger"></i>
</button>

What is the difference between Select and Project Operations

PROJECT eliminates columns while SELECT eliminates rows.

Add a new element to an array without specifying the index in Bash

As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.

$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array     # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h

Here's how to get the last index:

$ end=(${!array[@]})   # put all the indices in an array
$ end=${end[@]: -1}    # get the last one
$ echo $end
42

That illustrates how to get the last element of an array. You'll often see this:

$ echo ${array[${#array[@]} - 1]}
g

As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:

$ echo ${array[@]: -1}
i

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I had multiple providers specified in my web.config.

 <providers>
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>

I simply removed one of those and it worked.

I am using MySQL though, not TSQL

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

Using Composer's Autoload

In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

I was looking to autoload my package files using composer which I have under the dir structure given below.

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4 autoloading specification.

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

"autoload": {
        "psr-4": {
            "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

Best way to remove duplicate entries from a data table

Remove Duplicates

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
   Hashtable hTable = new Hashtable();
   ArrayList duplicateList = new ArrayList();

   //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
   //And add duplicate item value in arraylist.
   foreach (DataRow drow in dTable.Rows)
   {
      if (hTable.Contains(drow[colName]))
         duplicateList.Add(drow);
      else
         hTable.Add(drow[colName], string.Empty); 
   }

   //Removing a list of duplicate items from datatable.
   foreach (DataRow dRow in duplicateList)
      dTable.Rows.Remove(dRow);

   //Datatable which contains unique records will be return as output.
      return dTable;
}

Here Links below

http://www.dotnetspider.com/resources/4535-Remove-duplicate-records-from-table.aspx

http://www.dotnetspark.com/kb/94-remove-duplicate-rows-value-from-datatable.aspx

For remove duplicates in column

http://dotnetguts.blogspot.com/2007/02/removing-duplicate-records-from.html

SSL Proxy/Charles and Android trouble

For the newer emulator it might be helpful to launch from command line using:

emulator -netdelay none -netspeed full -avd <emulator_name> -http-proxy http://<ip-address>:8888

Make sure you follow @User9527's advice above as well for the rest of the setup

Using Google Translate in C#

Here is my slighly different code, solving also the encoding issue:

public string TranslateText(string input, string languagePair)
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = System.Text.Encoding.Default;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("TRANSLATED_TEXT"));
    result = result.Substring(result.IndexOf("'")+1);
    result = result.Substring(0, result.IndexOf("'"));
    return result;
}

Example of the function call:

var input_language = "en";
var output_language = "es";
var result = TranslateText("Hello", input_language + "|" + output_language);

The result will be "Hola"

Does Python have a package/module management system?

There are at least two, easy_install and its successor pip.

How can I get the last 7 characters of a PHP string?

Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:

$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
  mb_substr( $str, -7, null, 'UTF-8') ;

Rounding integer division (instead of truncating)

Some alternatives for division by 4

return x/4 + (x/2 % 2);
return x/4 + (x % 4 >= 2)

Or in general, division by any power of 2

return x/y + x/(y/2) % 2;    // or
return (x >> i) + ((x >> i - 1) & 1);  // with y = 2^i

It works by rounding up if the fractional part ? 0.5, i.e. the first digit ? base/2. In binary it's equivalent to adding the first fractional bit to the result

This method has an advantage in architectures with a flag register, because the carry flag will contain the last bit that was shifted out. For example on x86 it can be optimized into

shr eax, i
adc eax, 0

It's also easily extended to support signed integers. Notice that the expression for negative numbers is

(x - 1)/y + ((x - 1)/(y/2) & 1)

we can make it work for both positive and negative values with

int t = x + (x >> 31);
return (t >> i) + ((t >> i - 1) & 1);

Set Background cell color in PHPExcel

Here is how you do it in PHPSpreadsheet, the newest version of PHPExcel

$spreadsheet = new Spreadsheet();

$spreadsheet->getActiveSheet()->getStyle('A1:F1')->applyFromArray([
    'fill' => [
            'fillType' => Fill::FILL_SOLID,
            'startColor' => [
                'argb' => 'FFDBE2F1',
            ]           
    ],
]);

alternative approach:

$spreadsheet->getActiveSheet()
    ->getStyle('A1:F1')
    ->getFill()
    ->setFillType(Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFDBE2F1');

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

What is mutex and semaphore in Java ? What is the main difference?

Semaphore can be counted, while mutex can only count to 1.

Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections

Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".

Undefined index error PHP

To remove this error, in your html form you should do the following in enctype:

<form  enctype="multipart/form-data">

The following down is the cause of that error i.e if you start with form-data in enctype, so you should start with multipart:

<form enctype="form-data/multipart">

find filenames NOT ending in specific extensions on Unix?

Other solutions on this page aren't desirable if you have a long list of extensions -- maintaining a long sequence of -not -name 'this' -not -name 'that' -not -name 'other' would be tedious and error-prone -- or if the search is programmatic and the list of extensions is built at runtime.

For those situations, a solution that more clearly separates data (the list of extensions) and code (the parameters to find) may be desirable. Given a directory & file structure that looks like this:

.
+-- a
    +-- 1.txt
    +-- 15.xml
    +-- 8.dll
    +-- b
    ¦   +-- 16.xml
    ¦   +-- 2.txt
    ¦   +-- 9.dll
    ¦   +-- c
    ¦       +-- 10.dll
    ¦       +-- 17.xml
    ¦       +-- 3.txt
    +-- d
    ¦   +-- 11.dll
    ¦   +-- 18.xml
    ¦   +-- 4.txt
    ¦   +-- e
    ¦       +-- 12.dll
    ¦       +-- 19.xml
    ¦       +-- 5.txt
    +-- f
        +-- 13.dll
        +-- 20.xml
        +-- 6.txt
        +-- g
            +-- 14.dll
            +-- 21.xml
            +-- 7.txt

You can do something like this:

## data section, list undesired extensions here
declare -a _BADEXT=(xml dll)

## code section, this never changes
BADEXT="$( IFS="|" ; echo "${_BADEXT[*]}" | sed 's/|/\\|/g' )"
find . -type f ! -regex ".*\.\($BADEXT\)"

Which results in:

./a/1.txt
./a/b/2.txt
./a/b/c/3.txt
./a/d/4.txt
./a/d/e/5.txt
./a/f/6.txt
./a/f/g/7.txt

You can change the extensions list without changing the code block.

NOTE doesn't work with native OSX find - use gnu find instead.

To show error message without alert box in Java Script

Setting innerHtml of input value wont do anything good here, try with other element like span, or just display previously made and hidden error message. You can set value of name field tho.

<head>
    <script type="text/javascript">
        function validate() {
            if (myform.fname.value.length == 0) {
                document.getElementById("fname").value = "this is invalid name ";
                document.getElementById("errorMessage").style.display = "block";
            }
        }
    </script>
</head>

<body>
    <form name="myform">First_Name
        <input type="text" id="fname" name="fname" onblur="validate()"></input> <span id="errorMessage" style="display:none;">name field must not be empty</span>

        <br>
        <br>Last_Name
        <input type="text" id="lname" name="lname" onblur="validate()"></input>
        <br>
        <input type="button" value="check" />
    </form>
</body>

FIDDLE

Java error: Implicit super constructor is undefined for default constructor

Another way is call super() with the required argument as a first statement in derived class constructor.

public class Sup {
    public Sup(String s) { ...}
}

public class Sub extends Sup {
    public Sub() { super("hello"); .. }
}

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

Close all infowindows in Google Maps API v3

Write this below line after script tag start.

previous_Window=null;

It will work 100%. by using this code

 radius= circle.getRadius()/1000;
 radius_mile= circle.getRadius()/1609.344;

 newRadious = 'This Circle Radius Covers Approx ' + radius.toFixed(1) + ' Km'+' <br> This circle Radius Covers Approx '+ radius_mile.toFixed(1)+ 'Miles';
            var infoWindow= new google.maps.InfoWindow({
              content: newRadious
              });
 infoWindow.setContent(newRadious)
 infoWindow.setPosition(circle.getCenter());
 if (previous_Window) 
  previous_Window.close();

  infoWindow.open(map);
  previous_Window=infoWindow;

How to enter command with password for git pull?

If you are looking to do this in a CI/CD script on Gitlab (gitlab-ci.yml). You could use

git pull $CI_REPOSITORY_URL

which will translate to something like:

git pull https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.gi

And I'm pretty sure the token it uses is a ephemeral/per job token - so the security hole with this method is greatly reduced.

Kill all processes for a given user

Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!

pkill -9 -u `id -u username`

Note: if you want to be nice remove -9, but it will not kill all kinds of processes.

How to use pull to refresh in Swift?

Details

  • Xcode Version 10.3 (10G8), Swift 5

Features

  • Ability to make "pull to refresh" programmatically
  • Protection from multi- "pull to refresh" events
  • Ability to continue animating of the activity indicator when view controller switched (e.g. in case of TabController)

Solution

import UIKit

class RefreshControl: UIRefreshControl {

    private weak var actionTarget: AnyObject?
    private var actionSelector: Selector?
    override init() { super.init() }

    convenience init(actionTarget: AnyObject?, actionSelector: Selector) {
        self.init()
        self.actionTarget = actionTarget
        self.actionSelector = actionSelector
        addTarget()
    }

    private func addTarget() {
        guard let actionTarget = actionTarget, let actionSelector = actionSelector else { return }
        addTarget(actionTarget, action: actionSelector, for: .valueChanged)
    }

    required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }

    func endRefreshing(deadline: DispatchTime? = nil) {
        guard let deadline = deadline else { endRefreshing(); return }
        DispatchQueue.global(qos: .default).asyncAfter(deadline: deadline) { [weak self] in
            DispatchQueue.main.async { self?.endRefreshing() }
        }
    }

    func refreshActivityIndicatorView() {
        guard let selector = actionSelector else { return }
        let _isRefreshing = isRefreshing
        removeTarget(actionTarget, action: selector, for: .valueChanged)
        endRefreshing()
        if _isRefreshing { beginRefreshing() }
        addTarget()
    }

    func generateRefreshEvent() {
        beginRefreshing()
        sendActions(for: .valueChanged)
    }
}

public extension UIScrollView {

    private var _refreshControl: RefreshControl? { return refreshControl as? RefreshControl }

    func addRefreshControll(actionTarget: AnyObject?, action: Selector, replaceIfExist: Bool = false) {
        if !replaceIfExist && refreshControl != nil { return }
        refreshControl = RefreshControl(actionTarget: actionTarget, actionSelector: action)
    }

    func scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: Bool = false) {
        _refreshControl?.refreshActivityIndicatorView()
        guard   let refreshControl = refreshControl,
                contentOffset.y != -refreshControl.frame.height else { return }
        setContentOffset(CGPoint(x: 0, y: -refreshControl.frame.height), animated: changeContentOffsetWithAnimation)
    }

    private var canStartRefreshing: Bool {
        guard let refreshControl = refreshControl, !refreshControl.isRefreshing else { return false }
        return true
    }

    func startRefreshing() {
        guard canStartRefreshing else { return }
        _refreshControl?.generateRefreshEvent()
    }

    func pullAndRefresh() {
        guard canStartRefreshing else { return }
        scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: true)
        _refreshControl?.generateRefreshEvent()
    }

    func endRefreshing(deadline: DispatchTime? = nil) { _refreshControl?.endRefreshing(deadline: deadline) }
}

Usage

// Add refresh control to UICollectionView / UITableView / UIScrollView
private func setupTableView() {
    let tableView = UITableView()
    // ...
    tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
}

@objc func refreshData(_ refreshControl: UIRefreshControl) {
    tableView?.endRefreshing(deadline: .now() + .seconds(3))
}

// Stop refreshing in UICollectionView / UITableView / UIScrollView
tableView.endRefreshing()

// Simulate pull to refresh in UICollectionView / UITableView / UIScrollView
tableView.pullAndRefresh()

Full Sample

Do not forget to add the solution code here

import UIKit

class ViewController: UIViewController {

    private weak var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
    }

    private func setupTableView() {
        let tableView = UITableView()
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.dataSource = self
        tableView.delegate = self
        tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
        self.tableView = tableView
    }
}

extension ViewController {
    @objc func refreshData(_ refreshControl: UIRefreshControl) {
        print("refreshing")
        tableView?.endRefreshing(deadline: .now() + .seconds(3))
    }
}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.pullAndRefresh()
    }
}

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

Drop Down Menu/Text Field in one

I like jQuery Token input. Actually prefer the UI over some of the other options mentioned above.

http://loopj.com/jquery-tokeninput/

Also see: http://railscasts.com/episodes/258-token-fields for an explanation

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

Get the last non-empty cell in a column in Google Sheets

To find the last non-empty cell you can use INDEX and MATCH functions like this:

=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))

I think this is a little bit faster and easier.

WHERE clause on SQL Server "Text" data type

Please try this

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR, CastleType) = 'foo'

How to send data with angularjs $http.delete() request?

You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.

Otherwise I guess you can just pass the user id as part of the query params? Something like

$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...

How do I cancel form submission in submit button onclick event?

This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.

<script>
document.getElementById(id of the form).addEventListener(
    "submit",
    function(event)
    {
        if(validData() === false)
        {
            event.preventDefault();
        }
    },
    false
);

The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.

P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

How to get the first and last date of the current year?

Try this:

DATE_FORMAT(NOW(),'01/01/%Y')
DATE_FORMAT(NOW(),'31/12/%Y')

Html helper for <input type="file" />

I had this same question a while back and came across one of Scott Hanselman's posts:

Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks

Hope this helps.

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

What is the best way to conditionally apply attributes in AngularJS?

I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"

The same approach should work for other attribute types.

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)