Programs & Examples On #Entity model

Can I fade in a background image (CSS: background-image) with jQuery?

You can fade your background-image in various ways since Firefox 4 ...

Your CSS:

.box {
    background: #CCCCCC;
    -webkit-transition: background 0.5s linear;
    -moz-transition: background 0.5s linear;
    -o-transition: background 0.5s linear;
    transition: background 0.5s linear;
    }
.box:hover {
    background: url(path/to/file.png) no-repeat #CCCCCC;
    }

Your XHTML:

<div class="box">
    Some Text …
</div>

And thats it.

auto refresh for every 5 mins

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page

 <meta http-equiv="refresh" content="300">

Using Script:

            setInterval(function() {
                  window.location.reload();
                }, 300000); 

What are functional interfaces used for in Java 8?

Functional Interfaces: An interface is called a functional interface if it has a single abstract method irrespective of the number of default or static methods. Functional Interface are use for lamda expression. Runnable, Callable, Comparable, Comparator are few examples of Functional Interface.

KeyNotes:

  • Annotation @FunctionalInterface is used(Optional).
  • It should have only 1 abstract method(irrespective of number of default and static methods).
  • Two abstract method gives compilation error(Provider @FunctionalInterface annotation is used).

This thread talks more in detail about what benefit functional Interface gives over anonymous class and how to use them.

How do I set the proxy to be used by the JVM

The following shows how to set in Java a proxy with proxy user and proxy password from the command line, which is a very common case. You should not save passwords and hosts in the code, as a rule in the first place.

Passing the system properties in command line with -D and setting them in the code with System.setProperty("name", "value") is equivalent.

But note this

Example that works:

C:\temp>java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps.proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection

But the following does not work:

C:\temp>java com.andreas.JavaNetHttpConnection -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit

The only difference is the position of the system properties! (before and after the class)

If you have special characters in password, you are allowed to put it in quotes "@MyPass123%", like in the above example.

If you access an HTTPS service, you have to use https.proxyHost, https.proxyPort etc.

If you access an HTTP service, you have to use http.proxyHost, http.proxyPort etc.

AngularJS - Create a directive that uses ng-model

This is a little late answer, but I found this awesome post about NgModelController, which I think is exactly what you were looking for.

TL;DR - you can use require: 'ngModel' and then add NgModelController to your linking function:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

This way, no hacks needed - you are using Angular's built-in ng-model

jQuery validate: How to add a rule for regular expression validation?

Have you tried this??

$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })

Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.

How do I make a WPF TextBlock show my text on multiple lines?

Use Linebreak:

<TextBlock>
        <Run Text="Line1"/>
        <LineBreak/>
        <Run Text="Line2" FontStyle="Italic" FontSize="9"/>
        <LineBreak/>
        <Run Text="Line3"/>
    </TextBlock>

Refer this: https://social.msdn.microsoft.com/Forums/vstudio/en-US/51a3ffe4-ec82-404a-9a99-6672f2a6842b/how-to-give-multiline-in-textblock?forum=wpf

Thanks,

RDV

How to test enum types?

I agree with aberrant80.

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

I would expand on it by adding that unit testings an Enum can be very useful. If you work in a large code base, build time starts to mount up and a unit test can be a faster way to verify functionality (tests only build their dependencies). Another really big advantage is that other developers cannot change the functionality of your code unintentionally (a huge problem with very large teams).

And with all Test Driven Development, tests around an Enums Methods reduce the number of bugs in your code base.

Simple Example

public enum Multiplier {
    DOUBLE(2.0),
    TRIPLE(3.0);

    private final double multiplier;

    Multiplier(double multiplier) {
        this.multiplier = multiplier;
    }

    Double applyMultiplier(Double value) {
        return multiplier * value;
    }

}

public class MultiplierTest {

    @Test
    public void should() {
        assertThat(Multiplier.DOUBLE.applyMultiplier(1.0), is(2.0));
        assertThat(Multiplier.TRIPLE.applyMultiplier(1.0), is(3.0));
    }
}

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

For me was because I put the animation name inside square brackets.

<div [@animation]></div>

But after I removed the bracket all worked fine (In Angular 9.0.1):

<div @animation></div>

How to create a DB for MongoDB container on start up?

The official mongo image has merged a PR to include the functionality to databases and admin users at startup.

The database initialisation will run scripts in /docker-entrypoint-initdb.d/ when there is nothing populated in the /data/db directory.

Database Initialisation

The mongo container image provides the /docker-entrypoint-initdb.d/ path to deploy custom .js or .sh setup scripts that will be run once on database initialisation. .js scripts will be run against test by default or MONGO_INITDB_DATABASE if defined in the environment.

COPY mysetup.sh /docker-entrypoint-initdb.d/

or

COPY mysetup.js /docker-entrypoint-initdb.d/

A simple initialisation mongo shell javascript file that demonstrates setting up the container collection with data, logging and how to exit with an error (for result checking).

let error = true

let res = [
  db.container.drop(),
  db.container.createIndex({ myfield: 1 }, { unique: true }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]

printjson(res)

if (error) {
  print('Error, exiting')
  quit(1)
}

Admin User Setup

The environment variables to control "root" user setup are

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

Example

docker run -d \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  mongod

or Dockerfile

FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password

You don't need to use --auth on the command line as the docker entrypoint.sh script adds this in when it detects the environment variables exist.

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

Click a button programmatically - JS

When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.

This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.

I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.

What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.

The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.

I also made a point to test for the element before attempting to assign values to it.

window.setTimeout(function() { if( document.getElementById("book") ) { // Code goes here }, 400 /* but after 400 ms */);

This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.

System.web.mvc missing

Add the reference again from ./packages/Microsoft.AspNet.Mvc.[version]/lib/net45/System.Web.Mvc.dll

Can I pass column name as input parameter in SQL stored Procedure

First Run;

CREATE PROCEDURE sp_First @columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN

    DECLARE @query NVARCHAR(MAX)

    SET @query = 'SELECT ' + @columnname + ' FROM Table_1'

    EXEC(@query)

END

Second Run;

EXEC sp_First 'COLUMN_Name'

linq query to return distinct field values from a list of objects

If just want to user pure Linq, you can use groupby:

List<obj> distinct =
  objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();

If you want a method to be used all across the app, similar to what MoreLinq does:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (!seenKeys.Contains(keySelector(element)))
        {
            seenKeys.Add(keySelector(element));
            yield return element;
        }
    }
}

Using this method to find the distinct values using just the Id property, you could use:

var query = objs.DistinctBy(p => p.TypeId);

you can use multiple properties:

var query = objs.DistinctBy(p => new { p.TypeId, p.Name });

Why does "npm install" rewrite package-lock.json?

In the future, you will be able to use a --from-lock-file (or similar) flag to install only from the package-lock.json without modifying it.

This will be useful for CI, etc. environments where reproducible builds are important.

See https://github.com/npm/npm/issues/18286 for tracking of the feature.

Button inside of anchor link works in Firefox but not in Internet Explorer?

You cannot have a button inside an a tag. You can do some javascript to make it work however.

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

How do I import the javax.servlet API in my Eclipse project?

I was getting a null pointer exception during project creation related to "Dynamic Web Module".

To get the project to compile (that is, to javax.servlet to import successfully) I had to go to project's Properties, pick Project Facets in the sidebar, tick Dynamic Web Module and click Apply.

Surprisingly, this time "Dynamic Web Module" facet installed correctly, and import started to work.

How to use phpexcel to read data and insert into database?

    if($this->mng_auth->get_language()=='en')
          {
                    $excel->getActiveSheet()->setRightToLeft(false); 
          }
                else
                {  
                    $excel->getActiveSheet()->setRightToLeft(true); 
                }

       $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                            'color' => array('argb' => '00000000'),
                    ),
                ),
            );

          //SET property
          $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->applyFromArray($styleArray);


    $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->getAlignment()->setWrapText(true); 


$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->applyFromArray($styleArray);  

$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->getAlignment()->setWrapText(true); 

jQuery validation: change default error message

You can specify your own messages in the validate call. Lifting and abbreviating this code from the Remember the Milk signup form used in the Validation plugin documentation (http://jquery.bassistance.de/validate/demo/milk/), you can easily specify your own messages:

var validator = $("#signupform").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2,
            remote: "users.php"
        }
    },
    messages: {
        firstname: "Enter your firstname",
        lastname: "Enter your lastname",
        username: {
            required: "Enter a username",
            minlength: jQuery.format("Enter at least {0} characters"),
            remote: jQuery.format("{0} is already in use")
        }
    }
});

The complete API for validate(...) : http://jqueryvalidation.org/validate

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

As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines

books.author This object type represents a single author of a book.

books.book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

books.quotes
Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

books.rates
Returns no data as of April 4, 2018.

An action representing someone rating a book.

books.reads
Returns no data as of April 4, 2018.

An action representing someone reading a book.

books.wants_to_read
Returns no data as of April 4, 2018.

An action representing someone wanting to read a book.

business.business This object type represents a place of business that has a location, operating hours and contact information.

fitness.bikes
Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

fitness.runs
Returns no data as of April 4, 2018.

An action representing someone running a course.

fitness.walks
Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

music.listens
Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

music.playlists
Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.

music.song This object type represents a single song.

news.publishes An action representing someone publishing a news article.

news.reads
Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.

product.group This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user.

restaurant.menu This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items.

restaurant.restaurant This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.

video.movie This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the video.movie or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

video.rates
Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

video.wants_to_watch
Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.

video.watches
Returns no data as of April 4, 2018.

An action representing someone watching video content.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

All the solutions here failed to work on my VS2013, however I put the #define _CRT_SECURE_NO_WARNINGS in the stdafx.h just before the #pragma once and all warnings were suppressed. Note: I only code for prototyping purposes to support my research so please make sure you understand the implications of this method when writing your code.

Hope this helps

Detecting user leaving page with react-router

In react-router v2.4.0 or above and before v4 there are several options

  1. Add function onLeave for Route
 <Route
      path="/home"
      onEnter={ auth }
      onLeave={ showConfirm }
      component={ Home }
    >
    
  1. Use function setRouteLeaveHook for componentDidMount

You can prevent a transition from happening or prompt the user before leaving a route with a leave hook.

const Home = withRouter(
  React.createClass({

    componentDidMount() {
      this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
    },

    routerWillLeave(nextLocation) {
      // return false to prevent a transition w/o prompting the user,
      // or return a string to allow the user to decide:
      // return `null` or nothing to let other hooks to be executed
      //
      // NOTE: if you return true, other hooks will not be executed!
      if (!this.state.isSaved)
        return 'Your work is not saved! Are you sure you want to leave?'
    },

    // ...

  })
)

Note that this example makes use of the withRouter higher-order component introduced in v2.4.0.

However these solution doesn't quite work perfectly when changing the route in URL manually

In the sense that

  • we see the Confirmation - ok
  • contain of page doesn't reload - ok
  • URL doesn't changes - not okay

For react-router v4 using Prompt or custom history:

However in react-router v4 , its rather easier to implement with the help of Prompt from'react-router

According to the documentation

Prompt

Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a <Prompt>.

import { Prompt } from 'react-router'

<Prompt
  when={formIsHalfFilledOut}
  message="Are you sure you want to leave?"
/>

message: string

The message to prompt the user with when they try to navigate away.

<Prompt message="Are you sure you want to leave?"/>

message: func

Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.

<Prompt message={location => (
  `Are you sure you want to go to ${location.pathname}?`
)}/>

when: bool

Instead of conditionally rendering a <Prompt> behind a guard, you can always render it but pass when={true} or when={false} to prevent or allow navigation accordingly.

In your render method you simply need to add this as mentioned in the documentation according to your need.

UPDATE:

In case you would want to have a custom action to take when user is leaving page, you can make use of custom history and configure your Router like

history.js

import createBrowserHistory from 'history/createBrowserHistory'
export const history = createBrowserHistory()

... 
import { history } from 'path/to/history';
<Router history={history}>
  <App/>
</Router>

and then in your component you can make use of history.block like

import { history } from 'path/to/history';
class MyComponent extends React.Component {
   componentDidMount() {
      this.unblock = history.block(targetLocation => {
           // take your action here     
           return false;
      });
   }
   componentWillUnmount() {
      this.unblock();
   }
   render() {
      //component render here
   }
}

How to align flexbox columns left and right?

I came up with 4 methods to achieve the results. Here is demo

Method 1:

#a {
    margin-right: auto;
}

Method 2:

#a {
    flex-grow: 1;
}

Method 3:

#b {
    margin-left: auto;
}

Method 4:

#container {
    justify-content: space-between;
}

Presto SQL - Converting a date string to date format

SQL 2003 standard defines the format as follows:

<unquoted timestamp string> ::= <unquoted date string> <space> <unquoted time string>
<date value> ::= <years value> <minus sign> <months value> <minus sign> <days value>
<time value> ::= <hours value> <colon> <minutes value> <colon> <seconds value>

There are some definitions in between that just link back to these, but in short YYYY-MM-DD HH:MM:SS with optional .mmm milliseconds is required to work on all SQL databases.

LINUX: Link all files from one to another directory

ln -s /mnt/usr/lib/* /usr/lib/

I guess, this belongs to superuser, though.

when do you need .ascx files and how would you use them?

Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Well, the documentation does actually state that

CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.

as the very first thing, which obviusly means that you need to do a new server request. A redirect, a refresh, a link or some other mean to send the user to the next request.

Why use flashdata if you are using it in the same request, anyway? You'd might as well not use flashdata or use a regular session.

kubectl apply vs kubectl create?

These are imperative commands :

kubectl run = kubectl create deployment

Advantages:

  • Simple, easy to learn and easy to remember.
  • Require only a single step to make changes to the cluster.

Disadvantages:

  • Do not integrate with change review processes.
  • Do not provide an audit trail associated with changes.
  • Do not provide a source of records except for what is live.
  • Do not provide a template for creating new objects.

These are imperative object config:

kubectl create -f your-object-config.yaml

kubectl delete -f your-object-config.yaml

kubectl replace -f your-object-config.yaml

Advantages compared to imperative commands:

  • Can be stored in a source control system such as Git.
  • Can integrate with processes such as reviewing changes before push and audit trails.
  • Provides a template for creating new objects.

Disadvantages compared to imperative commands:

  • Requires basic understanding of the object schema.
  • Requires the additional step of writing a YAML file.

Advantages compared to declarative object config:

  • Simpler and easier to understand.
  • More mature after Kubernetes version 1.5.

Disadvantages compared to declarative object configuration:

  • Works best on files, not directories.
  • Updates to live objects must be reflected in configuration files, or they will be lost during the next replacement.

These are declarative object config

kubectl diff -f configs/

kubectl apply -f configs/

Advantages compared to imperative object config:

  • Changes made directly to live objects are retained, even if they are not merged back into the configuration files.
  • Better support for operating on directories and automatically detecting operation types (create, patch, delete) per-object.

Disadvantages compared to imperative object configuration:

  • Harder to debug and understand results when they are unexpected.
  • Partial updates using diffs create complex merge and patch operations.

Python list / sublist selection -1 weirdness

In list[first:last], last is not included.

The 10th element is ls[9], in ls[0:10] there isn't ls[10].

Finishing current activity from a fragment

Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.

Instead, I found that I can change views back the the parent activity by using this statement: setContentView(R.layout.activity_main);

This returns me back to the parent activity.

I hope that this helps someone else who may be looking for this.

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Entity Framework Query for inner join

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]
       -- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
    ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1

How can I find script's directory?

This worked for me (and I found it via the this stackoverflow question)

os.path.realpath(__file__)

MySQL Orderby a number, Nulls last

MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:

SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC

It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position ASC.

A good reference is here http://troels.arvin.dk/db/rdbms#select-order_by

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

I guess this should work. I solved my problem with this.

$ sudo yum clean all

$ sudo yum --disablerepo="epel" update nss

Programmatically add custom event in the iPhone Calendar

Working code in Swift-4.2

import UIKit
import EventKit
import EventKitUI

class yourViewController: UIViewController{

    let eventStore = EKEventStore()

    func addEventToCalendar() {

    eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
        DispatchQueue.main.async {
            if (granted) && (error == nil) {
                let event = EKEvent(eventStore: self.eventStore)
                event.title = self.headerDescription
                event.startDate = self.parse(self.requestDetails.value(forKey: "session_time") as? String ?? "")
                event.endDate = self.parse(self.requestDetails.value(forKey: "session_end_time") as? String ?? "")
                let eventController = EKEventEditViewController()
                eventController.event = event
                eventController.eventStore = self.eventStore
                eventController.editViewDelegate = self
                self.present(eventController, animated: true, completion: nil)

            }
        }


       })
    }

}

Now we will get the event screen and here you can also modify your settings:

enter image description here

Now add delegate method to handle Cancel and add the event button action of event screen:

    extension viewController: EKEventEditViewDelegate {

    func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
        controller.dismiss(animated: true, completion: nil)

    }
}

Note: Don't forget to add NSCalendarsUsageDescription key into info plist.

CSS to stop text wrapping under image

Very simple answer for this problem that seems to catch a lot of people:

<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>

    img {
        float: left;
    }
    p {
        overflow: hidden;
    }

See example: http://jsfiddle.net/vandigroup/upKGe/132/

S3 - Access-Control-Allow-Origin Header

This is a simple way to make this work.

I know this is an old question, but still is hard to find a solution.

To start, this worked for me on a project built with Rails 4, Paperclip 4, CamanJS, Heroku and AWS S3.


You have to request your image using the crossorigin: "anonymous" parameter.

    <img href="your-remote-image.jpg" crossorigin="anonymous"> 

Add your site URL to CORS in AWS S3. Here is a refference from Amazon about that. Pretty much, just go to your bucket, and then select "Properties" from the tabs on the right, open "Permissions tab and then, click on "Edit CORS Configuration".

Originally, I had < AllowedOrigin> set to *. Just change that asterisk to your URL, be sure to include options like http:// and https:// in separate lines. I was expecting that the asterisk accepts "All", but apparently we have to be more specific than that.

This is how it looks for me.

enter image description here

How to recognize swipe in all 4 directions

After digging around for a while:

The shortest way to add swipes for all 4 directions is:

override func viewDidLoad() {
    super.viewDidLoad()    
    for direction in [UISwipeGestureRecognizer.Direction.down, .up, .left, .right]{
        let swipeGest = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(_:)))
        swipeGest.direction = direction
        self.view.addGestureRecognizer(swipeGest)
    }
} 

@objc func swipeAction(_ gesture: UISwipeGestureRecognizer){
    switch gesture.direction {
    case UISwipeGestureRecognizer.Direction.right:
        print("Swiped right")
    case UISwipeGestureRecognizer.Direction.down:
        print("Swiped down")
    case UISwipeGestureRecognizer.Direction.left:
        print("Swiped left")
    case UISwipeGestureRecognizer.Direction.up:
        print("Swiped up")
    default: break
}

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

You can fix this issue as follows:

  • Open the IntelliJ preferences
  • Go to Build, Execution, Deployment > Compiler > Kotlin Compiler BUT Other Settings > Kotlin compiler if Android Studio > 3.4
  • Change the Target JVM version to 1.8
  • Click Apply

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

  1. Please check current version of your Kotlin in below path,

    C:\Program Files\Android\Android Studio\gradle\m2repository\org\jetbrains\kotlin\kotlin-stdlib\1.0.5

change to that version (1.0.5) in project level gradle file.

You can see in your above path does not mentioned any Java - jre version, so remove in your app level gradle file as below,

compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

How to write LaTeX in IPython Notebook?

You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.

Alternatively, Latex section of the iPython notebook tutorial explains this well.

You can either do:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")

or do this:

%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

More info found in this link

Uploading images using Node.js, Express, and Mongoose

I know that the original question related to specific versions, but it also referred to the "latest" - @JohnAllen 's post is no longer relevant due to Expressjs bodyParser and connect-form

This demonstrates the easy to use in-built bodyParser():

 /**
 * Module dependencies.
 */

var express = require('express')

var app = express()
app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/home/svn/rest-api/uploaded' }))

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

app.post('/', function(req, res, next){

    res.send('Uploaded: ' + req.files.image.name)
    return next()

});

app.listen(3000);
console.log('Express app started on port 3000');

Python 3 sort a dict by its values

To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDict from the standard library.

If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?

In Java, what does NaN mean?

Means Not a Number. It is a common representation for an impossible numeric value in many programming languages.

How to check for file lock?

You could call LockFile via interop on the region of file you are interested in. This will not throw an exception, if it succeeds you will have a lock on that portion of the file (which is held by your process), that lock will be held until you call UnlockFile or your process dies.

How do I apply CSS3 transition to all properties except background-position?

Here's a solution that also works on Firefox:

transition: all 0.3s ease, background-position 1ms;

I made a small demo: http://jsfiddle.net/aWzwh/

Connecting to smtp.gmail.com via command line

Gmail require SMTP communication with their server to be encrypted. Although you're opening up a connection to Gmail's server on port 465, unfortunately you won't be able to communicate with it in plaintext as Gmail require you to use STARTTLS/SSL encryption for the connection.

Warning about SSL connection when connecting to MySQL database

This was OK for me:

this.conn = (Connection)DriverManager
    .getConnection(url + dbName + "?useSSL=false", userName, password);

Failed to decode downloaded font

Changing format('woff') to format('font-woff') solves the problem.

Just a little change compared to Germano Plebani's answer

 @font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('font-woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

Please check if your browser sources can open it and what is the type

Remove all git files from a directory?

How to remove all .git directories under a folder in Linux.

Run this find command, it will list all .git directories under the current folder:

find . -type d -name ".git" \
&& find . -name ".gitignore" \
&& find . -name ".gitmodules"

Prints:

./.git
./.gitmodules
./foobar/.git
./footbar2/.git
./footbar2/.gitignore

There should only be like 3 or 4 .git directories because git only has one .git folder for every project. You can rm -rf yourpath each of the above by hand.

If you feel like removing them all in one command and living dangerously:

//Retrieve all the files named ".git" and pump them into 'rm -rf'
//WARNING if you don't understand why/how this command works, DO NOT run it!

( find . -type d -name ".git" \
  && find . -name ".gitignore" \
  && find . -name ".gitmodules" ) | xargs rm -rf

//WARNING, if you accidentally pipe a `.` or `/` or other wildcard
//into xargs rm -rf, then the next question you will have is: "why is
//the bash ls command not found?  Requiring an OS reinstall.

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.

How to increment variable under DOS?

I've found my own solution.

Download FreeDOS from here: http://chtaube.eu/computers/freedos/bootable-usb/

Then using my Counter.exe file (which basically generates a Counter.txt file and increments the number inside every time it's being called), I can assign the value of the number to a variable using:

Set /P Variable =< Counter.txt

Then, I can check if it has run 250 cycles by doing:

if %variable%==250 echo PASS

BTW, I still can't use Set /A since FreeDOS doesn't support this command, but at least it supports the Set /P command.

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How do you clear a stringstream variable?

For all the standard library types the member function empty() is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".

The clear() member function is inherited from ios and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit (end-of-file), then calling clear() will set the error state back to goodbit (no error).

For clearing the contents of a stringstream, using:

m.str("");

is correct, although using:

m.str(std::string());

is technically more efficient, because you avoid invoking the std::string constructor that takes const char*. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.

How to remove listview all items

You can only use

 lv.setAdapter(null);

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

open existing java project in eclipse

Simple, you just open klik file -> import -> General -> existing project into workspace -> browse file in your directory.

(I'am used Eclipse Mars)

What is an efficient way to implement a singleton pattern in Java?

Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.

There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.

How to overlay image with color in CSS?

In helpshift, they used the class home-page as

HTML

<div class="page home-page">...</div>

CSS

.home-page {
    background: transparent url("../images/backgrounds/image-overlay.png") repeat 0 0;
    background: rgba(39,62,84,0.82);
    overflow: hidden;
    height: 100%;
    z-index: 2;
}

you can try similar like this

Sorting an Array of int using BubbleSort

You're only making one pass through your array! Bubble sort requires you to keep looping until you find that you are no longer doing any swapping; hence the running time of O(n^2).

Try this:

public void sortArray(int[] x) {
    boolean swapped = true;
    while (swapped) {
       swapped = false;
       for(int i=1; i<x.length; i++) {
           int temp=0;
           if(x[i-1] > x[i]) {
               temp = x[i-1];
                x[i-1] = x[i];
                x[i] = temp;
                swapped = true;
            }
        }
    }
}

Once swapped == false at the end of a loop, you have made a whole pass without finding any instances where x[i-1] > x[i] and, hence, you know the array is sorted. Only then can you terminate the algorithm.

You can also replace the outer while loop with a for loop of n+1 iterations, which will guarantee that the array is in order; however, the while loop has the advantage of early termination in a better-than-worst-case scenario.

Sample database for exercise

If you want a big database of real data to play with, you could sign up for the Netflix Prize contest and get access to their data, which is pretty large (a few gigs of entries).

3rd party edit

The URL above does not contain the dataset anylonger (october 2016). The wikipedia page about the Netflix Prize reports that a law suit was settled regarding privacy concerns.

How to set the locale inside a Debian/Ubuntu Docker container?

Put in your Dockerfile something adapted from

# Set the locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && \
    locale-gen
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8     

If you run Debian or Ubuntu, you also need to install locales to have locale-gen with

apt-get -y install locales

this is extracted from the very good post on that subject, from

http://jaredmarkell.com/docker-and-locales/

1 = false and 0 = true?

I suspect it's just following the Linux / Unix standard for returning 0 on success.

Does it really say "1" is false and "0" is true?

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

get next sequence value from database using hibernate

I found the solution:

public class DefaultPostgresKeyServer
{
    private Session session;
    private Iterator<BigInteger> iter;
    private long batchSize;

    public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
    {
        this.session=sess;
        batchSize = batchFetchSize;
        iter = Collections.<BigInteger>emptyList().iterator();
    }

        @SuppressWarnings("unchecked")
        public Long getNextKey()
        {
            if ( ! iter.hasNext() )
            {
                Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );

                iter = (Iterator<BigInteger>) query.list().iterator();
            }
            return iter.next().longValue() ;
        }

}

Writing file to web server - ASP.NET

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

Negative weights using Dijkstra's Algorithm

Since Dijkstra is a Greedy approach, once a vertice is marked as visited for this loop, it would never be reevaluated again even if there's another path with less cost to reach it later on. And such issue could only happen when negative edges exist in the graph.


A greedy algorithm, as the name suggests, always makes the choice that seems to be the best at that moment. Assume that you have an objective function that needs to be optimized (either maximized or minimized) at a given point. A Greedy algorithm makes greedy choices at each step to ensure that the objective function is optimized. The Greedy algorithm has only one shot to compute the optimal solution so that it never goes back and reverses the decision.

In Python, how to check if a string only contains certain characters?

Final(?) edit

Answer, wrapped up in a function, with annotated interactive session:

>>> import re
>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):
...     return not bool(search(strg))
...
>>> special_match("")
True
>>> special_match("az09.")
True
>>> special_match("az09.\n")
False
# The above test case is to catch out any attempt to use re.match()
# with a `$` instead of `\Z` -- see point (6) below.
>>> special_match("az09.#")
False
>>> special_match("az09.X")
False
>>>

Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.

==== Earlier text ====

The [previously] accepted answer could use a few improvements:

(1) Presentation gives the appearance of being the result of an interactive Python session:

reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True

but match() doesn't return True

(2) For use with match(), the ^ at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the ^

(3) Should foster the use of raw string automatically unthinkingly for any re pattern

(4) The backslash in front of the dot/period is redundant

(5) Slower than the OP's code!

prompt>rem OP's version -- NOTE: OP used raw string!

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.43 usec per loop

prompt>rem OP's version w/o backslash

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.44 usec per loop

prompt>rem cleaned-up version of accepted answer

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))"
100000 loops, best of 3: 2.07 usec per loop

prompt>rem accepted answer

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))"
100000 loops, best of 3: 2.08 usec per loop

(6) Can produce the wrong answer!!

>>> import re
>>> bool(re.compile('^[a-z0-9\.]+$').match('1234\n'))
True # uh-oh
>>> bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n'))
False

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

Make sure you have set the new angular version configuration in your project. The new angular cli uses angular.json and not .angular-cli.json for its configuration.

Follow migration guide.

Javascript Cookie with no expiration date

YOU JUST CAN'T. There's no exact code to use for setting a forever cookie but an old trick will do, like current time + 10 years.

Just a note that any dates beyond January 2038 will doomed you for the cookies (32-bit int) will be deleted instantly. Wish for a miracle that that will be fixed in the near future. For 64-bit int, years around 2110 will be safe. As time goes by, software and hardware will change and may never adapt to older ones (the things we have now) so prepare the now for the future.

See Year 2038 problem

button image as form input submit button?

Make the submit button the main image you are using. So the form tags would come first then submit button which is your only image so the image is your clickable image form. Then just make sure to put whatever you are passing before the submit button code.

Android, getting resource ID from string?

In your res/layout/my_image_layout.xml

<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>

To grab that ImageView by its @+id value, inside your java code do this:

String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
                .getIdentifier(tileID, "id", activity.getPackageName()));

/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);  

How to print the full NumPy array, without truncation?

numpy.savetxt

numpy.savetxt(sys.stdout, numpy.arange(10000))

or if you need a string:

import StringIO
sio = StringIO.StringIO()
numpy.savetxt(sio, numpy.arange(10000))
s = sio.getvalue()
print s

The default output format is:

0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
...

and it can be configured with further arguments.

Note in particular how this also not shows the square brackets, and allows for a lot of customization, as mentioned at: How to print a Numpy array without brackets?

Tested on Python 2.7.12, numpy 1.11.1.

Merge (Concat) Multiple JSONObjects in Java

This is what I do

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * This class has all static functions to merge 2 objects into one
 */
public class MergeHelper {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * return a merge JsonNode, merge newJson into oldJson; override or insert
     * fields from newJson into oldJson
     * 
     * @param oldJson
     * @param newJson
     * @return
     */
    public static JsonNode mergeJsonObject(JsonNode oldJson, JsonNode newJson) {
        ObjectNode merged = objectMapper.createObjectNode();
        merged.setAll((ObjectNode) oldJson);
        merged.setAll((ObjectNode) newJson);
        return merged;
    }
}

HTML5 Dynamically create Canvas

 <html>
 <head></head>
 <body>
 <canvas id="canvas" width="300" height="300"></canvas>
 <script>
  var sun = new Image();
  var moon = new Image();
  var earth = new Image();
  function init() {
  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
  moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
  window.requestAnimationFrame(draw);
  }

  function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0, 0, 300, 300);

  ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
  ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)';
  ctx.save();
  ctx.translate(150, 150);

  // Earth
  var time = new Date();
  ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * 
  time.getMilliseconds());
  ctx.translate(105, 0);
  ctx.fillRect(10, -19, 55, 31); 
  ctx.drawImage(earth, -12, -12);

   // Moon
  ctx.save();
  ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * 
  time.getMilliseconds());
  ctx.translate(0, 28.5);
  ctx.drawImage(moon, -3.5, -3.5);
  ctx.restore();

  ctx.restore();

   ctx.beginPath();
   ctx.arc(150, 150, 105, 0, Math.PI * 2, false);
   ctx.stroke();

   ctx.drawImage(sun, 0, 0, 300, 300);

   window.requestAnimationFrame(draw);
    }

   init();
   </script>
   </body>
   </html>

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

What are the most-used vim commands/keypresses?

Here's a tip sheet I wrote up once, with the commands I actually use regularly:

References

General

  • Nearly all commands can be preceded by a number for a repeat count. eg. 5dd delete 5 lines
  • <Esc> gets you out of any mode and back to command mode
  • Commands preceded by : are executed on the command line at the bottom of the screen
  • :help help with any command

Navigation

  • Cursor movement: ?h ?j ?k l?
  • By words:
    • w next word (by punctuation); W next word (by spaces)
    • b back word (by punctuation); B back word (by spaces)
    • e end word (by punctuation); E end word (by spaces)
  • By line:
    • 0 start of line; ^ first non-whitespace
    • $ end of line
  • By paragraph:
    • { previous blank line; } next blank line
  • By file:
    • gg start of file; G end of file
    • 123G go to specific line number
  • By marker:
    • mx set mark x; 'x go to mark x
    • '. go to position of last edit
    • ' ' go back to last point before jump
  • Scrolling:
    • ^F forward full screen; ^B backward full screen
    • ^D down half screen; ^U up half screen
    • ^E scroll one line up; ^Y scroll one line down
    • zz centre cursor line

Editing

  • u undo; ^R redo
  • . repeat last editing command

Inserting

All insertion commands are terminated with <Esc> to return to command mode.

  • i insert text at cursor; I insert text at start of line
  • a append text after cursor; A append text after end of line
  • o open new line below; O open new line above

Changing

  • r replace single character; R replace multiple characters
  • s change single character
  • cw change word; C change to end of line; cc change whole line
  • c<motion> changes text in the direction of the motion
  • ci( change inside parentheses (see text object selection for more examples)

Deleting

  • x delete char
  • dw delete word; D delete to end of line; dd delete whole line
  • d<motion> deletes in the direction of the motion

Cut and paste

  • yy copy line into paste buffer; dd cut line into paste buffer
  • p paste buffer below cursor line; P paste buffer above cursor line
  • xp swap two characters (x to delete one character, then p to put it back after the cursor position)

Blocks

  • v visual block stream; V visual block line; ^V visual block column
    • most motion commands extend the block to the new cursor position
    • o moves the cursor to the other end of the block
  • d or x cut block into paste buffer
  • y copy block into paste buffer
  • > indent block; < unindent block
  • gv reselect last visual block

Global

  • :%s/foo/bar/g substitute all occurrences of "foo" to "bar"
    • % is a range that indicates every line in the file
    • /g is a flag that changes all occurrences on a line instead of just the first one

Searching

  • / search forward; ? search backward
  • * search forward for word under cursor; # search backward for word under cursor
  • n next match in same direction; N next match in opposite direction
  • fx forward to next character x; Fx backward to previous character x
  • ; move again to same character in same direction; , move again to same character in opposite direction

Files

  • :w write file to disk
  • :w name write file to disk as name
  • ZZ write file to disk and quit
  • :n edit a new file; :n! edit a new file without saving current changes
  • :q quit editing a file; :q! quit editing without saving changes
  • :e edit same file again (if changed outside vim)
  • :e . directory explorer

Windows

  • ^Wn new window
  • ^Wj down to next window; ^Wk up to previous window
  • ^W_ maximise current window; ^W= make all windows equal size
  • ^W+ increase window size; ^W- decrease window size

Source Navigation

  • % jump to matching parenthesis/bracket/brace, or language block if language module loaded
  • gd go to definition of local symbol under cursor; ^O return to previous position
  • ^] jump to definition of global symbol (requires tags file); ^T return to previous position (arbitrary stack of positions maintained)
  • ^N (in insert mode) automatic word completion

Show local changes

Vim has some features that make it easy to highlight lines that have been changed from a base version in source control. I have created a small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff

How to save local data in a Swift app?

For Swift 4.0, this got easier:

let defaults = UserDefaults.standard
//Set
defaults.set(passwordTextField.text, forKey: "Password")
//Get
let myPassword = defaults.string(forKey: "Password")

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

javascript : sending custom parameters with window.open() but its not working

if you want to pass POST variables, you have to use a HTML Form:

<form action="http://localhost:8080/login" method="POST" target="_blank">
    <input type="text" name="cid" />
    <input type="password" name="pwd" />
    <input type="submit" value="open" />
</form>

or:

if you want to pass GET variables in an URL, write them without single-quotes:

http://yourdomain.com/login?cid=username&pwd=password

here's how to create the string above with javascrpt variables:

myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");

in the document with that url, you have to read the GET parameters. if it's in php, use:

$_GET['username']

be aware: to transmit passwords that way is a big security leak!

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

How to parse freeform street/postal address out of text, and into components

No code? For shame!

Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).

But rather than cry, I decided to try:

This code works OK for parsing most Esri results for findAddressCandidate and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)

_x000D_
_x000D_
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
  var address = {_x000D_
    street: "",_x000D_
    city: "",_x000D_
    state: "",_x000D_
    postalCode: ""_x000D_
  };_x000D_
_x000D_
  // tokenize by space (retain commas in tokens)_x000D_
  var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
  var tokenCount = tokens.length;_x000D_
  var lastToken = tokens.pop();_x000D_
  if (_x000D_
    // if numeric assume postal code (ignore length, for now)_x000D_
    !isNaN(lastToken) ||_x000D_
    // if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
    lastToken.split("-").length - 1 === 1) {_x000D_
    address.postalCode = lastToken;_x000D_
    lastToken = tokens.pop();_x000D_
  }_x000D_
_x000D_
  if (lastToken && isNaN(lastToken)) {_x000D_
    if (address.postalCode.length && lastToken.length === 2) {_x000D_
      // assume state/province code ONLY if had postal code_x000D_
      // otherwise it could be a simple address like "714 S OAK ST"_x000D_
      // where "ST" for "street" looks like two-letter state code_x000D_
      // possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
      address.state = lastToken;_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
    if (address.state.length === 0) {_x000D_
      // check for special case: might have State name instead of State Code._x000D_
      var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found separator, ignore stuff on left side_x000D_
          tokens.push(lastToken); // put it back_x000D_
          break;_x000D_
        } else {_x000D_
          stateNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.state = stateNameParts.join(' ');_x000D_
      lastToken = tokens.pop();_x000D_
    }_x000D_
  }_x000D_
_x000D_
  if (lastToken) {_x000D_
    // here is where it gets trickier:_x000D_
    if (address.state.length) {_x000D_
      // if there is a state, then assume there is also a city and street._x000D_
      // PROBLEM: city may be multiple words (spaces)_x000D_
      // but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
      // most cities are single-name. It would be very helpful if we knew more context, like_x000D_
      // the name of the city user is in. But ignore that for now._x000D_
      // ideally would have zip code service or lookup to give city name for the zip code._x000D_
      var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
      // assumption / RULE: street and city must have comma delimiter_x000D_
      // addresses that do not follow this rule will be wrong only if city has space_x000D_
      // but don't care because Esri formats put comma before City_x000D_
      var streetNameParts = [];_x000D_
_x000D_
      // check remaining tokens from right-to-left for the first comma_x000D_
      while (2 + 2 != 5) {_x000D_
        lastToken = tokens.pop();_x000D_
        if (!lastToken) break;_x000D_
        else if (lastToken.endsWith(",")) {_x000D_
          // found end of street address (may include building, etc. - don't care right now)_x000D_
          // add token back to end, but remove trailing comma (it did its job)_x000D_
          tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
          streetNameParts = tokens;_x000D_
          break;_x000D_
        } else {_x000D_
          cityNameParts.unshift(lastToken);_x000D_
        }_x000D_
      }_x000D_
      address.city = cityNameParts.join(' ');_x000D_
      address.street = streetNameParts.join(' ');_x000D_
    } else {_x000D_
      // if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
      // reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
      // put last token back in list, then rejoin on space_x000D_
      tokens.push(lastToken);_x000D_
      address.street = tokens.join(' ');_x000D_
    }_x000D_
  }_x000D_
  // when parsing right-to-left hard to know if street only vs street + city/state_x000D_
  // hack fix for now is to shift stuff around._x000D_
  // assumption/requirement: will always have at least street part; you will never just get "city, state"  _x000D_
  // could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
  if (!address.city && address.state) {_x000D_
    address.city = address.state;_x000D_
    address.state = '';_x000D_
  }_x000D_
  if (!address.street) {_x000D_
    address.street = address.city;_x000D_
    address.city = '';_x000D_
  }_x000D_
_x000D_
  return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
  .filter(function(o) {_x000D_
    return o.length > 0_x000D_
  })_x000D_
  .map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll &amp; Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot uninstall angular-cli

This sometime happens when you had actually installed @angular/cli using yarn and not npm.

You can verify this by looking in to yarn's global install folder.

You can remove it from yarn using

yarn global remove @angular/cli

how to set active class to nav menu from twitter bootstrap

I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.

$(document).ready(function () {         
    $(function(){
        var current_page_URL = location.href;

        $( "a" ).each(function() {

            if ($(this).attr("href") !== "#") {

                var target_URL = $(this).prop("href");

                    if (target_URL == current_page_URL) {
                        $('nav a').parents('li, ul').removeClass('active');
                        $(this).parent('li').addClass('active');

                        return false;
                    }
            }
        }); }); });

Remove all constraints affecting a UIView

Using a Reusable Sequence

I decided to approach this in a more 'reusable' way. Since finding all constraints affecting a view is the basis for all of the above, I decided to implement a custom sequence that returns them all for me, along with the owning views.

First thing to do is define an extension on Arrays of NSLayoutConstraint that returns all elements affecting a specific view.

public extension Array where Element == NSLayoutConstraint {

    func affectingView(_ targetView:UIView) -> [NSLayoutConstraint] {

        return self.filter{

            if let firstView = $0.firstItem as? UIView,
                firstView == targetView {
                return true
            }

            if let secondView = $0.secondItem as? UIView,
                secondView == targetView {
                return true
            }

            return false
        }
    }
}

We then use that extension in a custom sequence that returns all constraints affecting that view, along with the views that actually own them (which can be anywhere up the view hierarchy)

public struct AllConstraintsSequence : Sequence {

    public init(view:UIView){
        self.view = view
    }

    public let view:UIView

    public func makeIterator() -> Iterator {
        return Iterator(view:view)
    }

    public struct Iterator : IteratorProtocol {

        public typealias Element = (constraint:NSLayoutConstraint, owningView:UIView)

        init(view:UIView){
            targetView  = view
            currentView = view
            currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
        }

        private let targetView  : UIView
        private var currentView : UIView
        private var currentViewConstraintsAffectingTargetView:[NSLayoutConstraint] = []
        private var nextConstraintIndex = 0

        mutating public func next() -> Element? {

            while(true){

                if nextConstraintIndex < currentViewConstraintsAffectingTargetView.count {
                    defer{nextConstraintIndex += 1}
                    return (currentViewConstraintsAffectingTargetView[nextConstraintIndex], currentView)
                }

                nextConstraintIndex = 0

                guard let superview = currentView.superview else { return nil }

                self.currentView = superview
                self.currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
            }
        }
    }
}

Finally we declare an extension on UIView to expose all the constraints affecting it in a simple property that you can access with a simple for-each syntax.

extension UIView {

    var constraintsAffectingView:AllConstraintsSequence {
        return AllConstraintsSequence(view:self)
    }
}

Now we can iterate all constraints affecting a view and do what we want with them...

List their identifiers...

for (constraint, _) in someView.constraintsAffectingView{
    print(constraint.identifier ?? "No identifier")
}

Deactivate them...

for (constraint, _) in someView.constraintsAffectingView{
    constraint.isActive = false
}

Or remove them entirely...

for (constraint, owningView) in someView.constraintsAffectingView{
    owningView.removeConstraints([constraint])
}

Enjoy!

Type definition in object literal in TypeScript

In your code:

var obj = {
  myProp: string;
};

You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):

var string = 'A string';

var obj = {
  property: string
};

However, what you want is that the object literal is typed. This can be achieved in various ways:

Interface:

interface myObj {
    property: string;
}

var obj: myObj = { property: "My string" };

Type alias:

type myObjType = {
    property: string
};

var obj: myObjType = { property: "My string" };

Object type literal:

var obj: { property: string; } = { property: "Mystring" };

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):
        print(x+y)

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()
b.call_a()

output: 3

How to remove the querystring and get only the url?

To remove the query string from the request URI, replace the query string with an empty string:

function request_uri_without_query() {
    $result = $_SERVER['REQUEST_URI'];
    $query = $_SERVER['QUERY_STRING'];
    if(!empty($query)) {
        $result = str_replace('?' . $query, '', $result);
    }
    return $result;
}

what is the difference between XSD and WSDL

WSDL (Web Services Description Language) describes your service and its operations - what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

It's a description of the behavior of the service - it's functionality.

XSD (Xml Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern) and so forth.

It's a description of datatypes and thus static properties of the service - it's about data.

Linux command (like cat) to read a specified quantity of characters

You can use dd to extract arbitrary chunks of bytes.

For example,

dd skip=1234 count=5 bs=1

would copy bytes 1235 to 1239 from its input to its output, and discard the rest.

To just get the first five bytes from standard input, do:

dd count=5 bs=1

Note that, if you want to specify the input file name, dd has old-fashioned argument parsing, so you would do:

dd count=5 bs=1 if=filename

Note also that dd verbosely announces what it did, so to toss that away, do:

dd count=5 bs=1 2>&-

or

dd count=5 bs=1 2>/dev/null

Sort a single String in Java

In Java 8 it can be done with:

String s = "edcba".chars()
    .sorted()
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
    .toString();

A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:

String sorted =
    Stream.of("edcba".split(""))
        .sorted()
        .collect(Collectors.joining());

change array size

If you really need to get it back into an array I find it easiest to convert the array to a list, expand the list then convert it back to an array.

        string[] myArray = new string[1] {"Element One"};
        // Convert it to a list
        List<string> resizeList = myArray.ToList();
        // Add some elements
        resizeList.Add("Element Two");
        // Back to an array
        myArray = resizeList.ToArray();
        // myArray has grown to two elements.

How to embed YouTube videos in PHP?

You can simply create a php input form for Varchar date,give it a varchar length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

         if(!/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2}$/.test($(this).val())){
                     alert('Date format incorrect (DD/MM/YY)');
                     $(this).datepicker('setDate', "");
                     return false;
                }

This code will validate date format DD/MM/YY

How to recursively find the latest modified file in a directory?

I found the command above useful, but for my case I needed to see the date and time of the file as well I had an issue with several files that have spaces in the names. Here is my working solution.

find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" " | sed 's/.*/"&"/' | xargs ls -l

Declaring multiple variables in JavaScript

ECMAScript 2015 introduced destructuring assignment which works pretty nice:

[a, b] = [1, 2]

a will equal 1 and b will equal 2.

How to redirect from one URL to another URL?

location.href = "Pagename.html";

Setting default values to null fields when mapping with Jackson

Only one proposed solution keeps the default-value when some-value:null was set explicitly (POJO readability is lost there and it's clumsy)

Here's how one can keep the default-value and never set it to null

@JsonProperty("some-value")
public String someValue = "default-value";

@JsonSetter("some-value")
public void setSomeValue(String s) {
    if (s != null) { 
        someValue = s; 
    }
}

Save child objects automatically using JPA Hibernate

In short set cascade type to all , will do a job; For an example in your model. Add Code like this . @OneToMany(mappedBy = "receipt", cascade=CascadeType.ALL) private List saleSet;

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

Its in the comments of the answers but nobody has posted this as the actual solution.

You just need to add a using statement at the top:

using Microsoft.AspNet.Identity;

angular 4: *ngIf with multiple conditions

You got a ninja ')'.

Try :

<div *ngIf="currentStatus !== 'open' || currentStatus !== 'reopen'">

Do we need type="text/css" for <link> in HTML5

The HTML5 spec says that the type attribute is purely advisory and explains in detail how browsers should act if it's omitted (too much to quote here). It doesn't explicitly say that an omitted type attribute is either valid or invalid, but you can safely omit it knowing that browsers will still react as you expect.

Making a flex item float right

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
    <div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
             divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div>another child </div>_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP Constants Containing Arrays?

Using explode and implode function we can improvise a solution :

$array = array('lastname', 'email', 'phone');
define('DEFAULT_ROLES', implode (',' , $array));
echo explode(',' ,DEFAULT_ROLES ) [1]; 

This will echo email.

If you want it to optimize it more you can define 2 functions to do the repetitive things for you like this :

//function to define constant
function custom_define ($const , $array) {
    define($const, implode (',' , $array));
}

//function to access constant  
function return_by_index ($index,$const = DEFAULT_ROLES) {
            $explodedResult = explode(',' ,$const ) [$index];
    if (isset ($explodedResult))
        return explode(',' ,$const ) [$index] ;
}

Hope that helps . Happy coding .

How to detect when WIFI Connection has been established in Android?

For all those who enjoying CONNECTIVITY_CHANGE broadcast, please note this is no more fired when app is in background in Android O.

https://developer.android.com/about/versions/o/background.html

How to change the color of an svg element?

You can try with filter hack:

.colorize-pink {
  filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}

.colorize-navy {
  filter: brightness(0.2) sepia(1) hue-rotate(180deg) saturate(5);
}

.colorize-blue {
  filter: brightness(0.5) sepia(1) hue-rotate(140deg) saturate(6);
}

How to check if an email address exists without sending an email?

Not really.....Some server may not check the "rcpt to:"

http://www.freesoft.org/CIE/RFC/1123/92.htm

Doing so is security risk.....

If the server do, you can write a bot to discovery every address on the server....

Java JTable setting Column Width

No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);

What is an attribute in Java?

¦ What is an attribute?

– A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members

¦ How else can it be called?

– field or instance variable

¦ How do you create one? What is the syntax?

– You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following: ;

Border for an Image view in Android?

Add a background Drawable like res/drawables/background.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@android:color/white" />
  <stroke android:width="1dp" android:color="@android:color/black" />
</shape>

Update the ImageView background in res/layout/foo.xml:

...
<ImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:padding="1dp"
  android:background="@drawable/background"
  android:src="@drawable/bar" />
...

Exclude the ImageView padding if you want the src to draw over the background.

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

JavaScript code for getting the selected value from a combo box

There is an unnecessary hashtag; change the code to this:

var e = document.getElementById("ticket_category_clone").value;

Convert date to datetime in Python

I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here's the code. Correct me if I'm wrong.

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
else:
     user_date = datetime.now()
print user_date

XCOPY switch to create specified directory if it doesn't exist?

You could use robocopy:

robocopy "$(TargetPath)" "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules" /E

Validate phone number with JavaScript

My regex of choice is:

/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

Valid formats:

(123) 456-7890
(123)456-7890
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725

How can I compile LaTeX in UTF8?

You needed to iconv your source.

That said, the TEX-based compiler invoked by latex doesn't really support variable-length encodings; it needs big libraries that tell it that certain bytes go together. Xelatex is Unicode-aware and works much better.

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body
        link.download = filename;
        link.href = uri;
        link.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

IIS - can't access page by ip address instead of localhost

In IIS Manager, I added a binding to the site specifying the IP address. Previously, all my bindings were host names.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Here is a simple expressjs solution if you just want to run this app locally and security is not a concern:

On your server.js or app.js file, add the following:

app.use('/local-files', express.static('/'));

That will serve your ENTIRE root directory under /local-files. Needless to say this is a really bad idea if you're planning to deploy this app anywhere other than your local machine.

Now, you can simply do:

<img src="/local-files/images/mypic.jps"/> 

note: I'm running macOS. If you're using Windows you may have to search and remove 'C:\' from the path string

Certificate has either expired or has been revoked

It's not a big issue i faced. Just clean the project and restart your xcode!! Hope it will be working for you! It's working for me. :)

Or First of all clean the project by holding Shift(?)+Command(?)+K or Select Product > Clean

Then

Go to XCode Menu> Preference

Select Account > Team > View Details

Select any Provisioning profile from Provisioning Profiles list

Right click > Select Show in Finder. Then you will see all lists of provisioning profiles

Select all provisionaling list from the folder and move it to trash

Download All provisioning profiles by clicking Download All below Provisioning Profile lists.

Now, Run again and it should Work!

Cannot find R.layout.activity_main

in 2019 I faced the same problem and I searched the internet and found the following which I am sharing with all.

In android studio letter R stands for the resources and this error occurs because of the build process not able to sync resources with your project. In other words, this error is caused when Android Studio can’t generate your R.java file correctly. This problem happens when you shift code to another system or while building the android project for the first time. So when you create a new activity or new class you will see an error message like “cannot resolve symbol r” with a red underline.

Below you can find the possible ways to fix cannot resolve symbol r in android studio.

Update Project Gradle To Latest Version Always use the latest version of Gradle to work android studio properly.

Sync Project With Gradle File Once you update the Gradle plugin you need to sync project with the Gradle file. Open android studio and click on Files > Sync Project with Gradle Files option.

Clean and Rebuild Project The most effective solution is the simplest: clean and rebuild your project. Select Build > Clean Project from the Android Studio toolbar, wait a few moments, and then build your project by selecting Build > Rebuild Project.

Invalidate Caches / Restart If you encounter this error after moving some files and directories around, then it’s possible that the R.layout error is being caused by a mismatch between Android Studio’s cache and your project’s current layout. If you suspect this may be the case, then select File > Invalidate Caches / Restart > Invalidate and Restart from Android Studio’s toolbar. Issues with the names of your resources can also prevent the R.java file from being created correctly, so check that you don't have multiple resources with the same name and that none of your file names contain invalid characters. Android Studio only supports lowercase a-z, 0-9, full stops and underscores, and a single invalid character can cause an R.layout error across your entire project, even if you don’t actually use this resource anywhere in your project!

My problem and its solution: In my case, I applied all the above but could not solve the problem. Thus I started a new project and pasted my code one by one and validated my code with running the app. Finally, at one point when I first deleted the code in colors.xml and copied and pasted code below in colors.xml file, I got the error.

<color name="bg_login">#26ae90</color>
<color name="bg_register">#2e3237</color>
<color name="bg_main">#428bca</color>
<color name="white">#ffffff</color>
<color name="input_login">#222222</color>
<color name="input_login_hint">#999999</color>
<color name="input_register">#888888</color>
<color name="input_register_bg">#3b4148</color>
<color name="input_register_hint">#5e6266</color>
<color name="btn_login">#26ae90</color>
<color name="btn_login_bg">#eceef1</color>
<color name="lbl_name">#333333</color>
<color name="btn_logut_bg">#ff6861</color>

when I undo my changes the error vanished again. Thus my code in colors.xml is not the code above and the code already in colors.xml i.e

<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="bg_login">#26ae90</color>
<color name="bg_register">#2e3237</color>
<color name="bg_main">#428bca</color>
<color name="white">#ffffff</color>
<color name="input_login">#222222</color>
<color name="input_login_hint">#999999</color>
<color name="input_register">#888888</color>
<color name="input_register_bg">#3b4148</color>
<color name="input_register_hint">#5e6266</color>
<color name="btn_login">#26ae90</color>
<color name="btn_login_bg">#eceef1</color>
<color name="lbl_name">#333333</color>
<color name="btn_logut_bg">#ff6861</color>

"Maybe its because i did not have color primary defined" Hope it will help someone like me who is new in programming.

How to resize an Image C#

Resize and save an image to fit under width and height like a canvas keeping image proportional

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Infra.Files
{
    public static class GenerateThumb
    {
        /// <summary>
        /// Resize and save an image to fit under width and height like a canvas keeping things proportional
        /// </summary>
        /// <param name="originalImagePath"></param>
        /// <param name="thumbImagePath"></param>
        /// <param name="newWidth"></param>
        /// <param name="newHeight"></param>
        public static void GenerateThumbImage(string originalImagePath, string thumbImagePath, int newWidth, int newHeight)
        {
            Bitmap srcBmp = new Bitmap(originalImagePath);
            float ratio = 1;
            float minSize = Math.Min(newHeight, newHeight);

            if (srcBmp.Width > srcBmp.Height)
            {
                ratio = minSize / (float)srcBmp.Width;
            }
            else
            {
                ratio = minSize / (float)srcBmp.Height;
            }

            SizeF newSize = new SizeF(srcBmp.Width * ratio, srcBmp.Height * ratio);
            Bitmap target = new Bitmap((int)newSize.Width, (int)newSize.Height);

            using (Graphics graphics = Graphics.FromImage(target))
            {
                graphics.CompositingQuality = CompositingQuality.HighSpeed;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    target.Save(thumbImagePath);
                }
            }
        }
    }
}

The transaction manager has disabled its support for remote/network transactions

In case others have the same issue:

I had a similar error happening. turned out I was wrapping several SQL statements in a transactions, where one of them executed on a linked server (Merge statement in an EXEC(...) AT Server statement). I resolved the issue by opening a separate connection to the linked server, encapsulating that statement in a try...catch then abort the transaction on the original connection in case the catch is tripped.

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

I suppose one thing that may be concerning you is whether or not the entries could change, so that the 2 becomes a different number, for instance. You can put your mind at ease here, because in Python, integers are immutable, meaning they cannot change after they are created.

Not everything in Python is immutable, though. For example, lists are mutable---they can change after being created. So for example, if you had a list of lists

>>> a = [[1], [2], [3]]
>>> a[0].append(7)
>>> a
[[1, 7], [2], [3]]

Here, I changed the first entry of a (I added 7 to it). One could imagine shuffling things around, and getting unexpected things here if you are not careful (and indeed, this does happen to everyone when they start programming in Python in some way or another; just search this site for "modifying a list while looping through it" to see dozens of examples).

It's also worth pointing out that x = x + [a] and x.append(a) are not the same thing. The second one mutates x, and the first one creates a new list and assigns it to x. To see the difference, try setting y = x before adding anything to x and trying each one, and look at the difference the two make to y.

How to alter a column and change the default value?

Accepted Answer works good.

In case of Invalid use of NULL value error, on NULL values, update all null values to default value in that column and then try to do the alter.

UPDATE foobar_data SET col = '{}' WHERE col IS NULL;

ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';

How to hide scrollbar in Firefox?

I tried everything and what worked best for my solution was to always have the vertical scrollbar show, and then add some negative margin to hide it.

This worked for IE11, FF60.9 and Chrome 80

body {
  -ms-overflow-style: none; /** IE11 */
  overflow-y: scroll;
  overflow-x: hidden;
  margin-right: -20px;
}

Identifying country by IP address

Yes, you can download the IP address ranges by country from https://lite.ip2location.com/ip-address-ranges-by-country

You can see that each country has multiple ranges and changes frequently.

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

Can't compile C program on a Mac after upgrade to Mojave

NOTE: The following is likely highly contextual and time-limited before the switch/general availability of macos Catalina 10.15. New laptop. I am writing this Oct 1st, 2019.

These specific circumstances are, I believe, what caused build problems for me. They may not apply in most other cases.

Context:

  • macos 10.14.6 Mojave, Xcode 11.0, right before the launch of macos Catalina 10.15. Newly purchased Macbook Pro.

  • failure on pip install psycopg2, which is, basically, a Python package getting compiled from source.

  • I have already carried out a number of the suggested adjustments in the answers given here.

My errors:

pip install psycopg2
Collecting psycopg2
  Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c29bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz
Installing collected packages: psycopg2
  Running setup.py install for psycopg2 ... error
    ERROR: Command errored out with exit status 1:
     command: xxxx/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/bk/_1cwm6dj3h1c0ptrhvr2v7dc0000gs/T/pip-install-z0qca56g/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/bk/_1cwm6dj3h1c0ptrhvr2v7dc0000gs/T/pip-install-z0qca56g/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/bk/_1cwm6dj3h1c0ptrhvr2v7dc0000gs/T/pip-record-ef126d8d/install-record.txt --single-version-externally-managed --compile --install-headers xxx/venv/include/site/python3.6/psycopg2


...
/usr/bin/clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -pipe -Os -isysroot/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=90615 -DHAVE_LO64=1 -I/Users/jluc/kds2/py2/venv/include -I/opt/local/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -I. -I/opt/local/include/postgresql96 -I/opt/local/include/postgresql96/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.14-x86_64-3.6/psycopg/psycopgmodule.o

    clang: warning: no such sysroot directory: 
'/Applications/Xcode.app/Contents/Developer/Platforms
                              ?the real error?
/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk' [-Wmissing-sysroot]
    In file included from psycopg/psycopgmodule.c:27:
    In file included from ./psycopg/psycopg.h:34:
    /opt/local/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m/Python.h:25:10: fatal error: 'stdio.h' file not found
                             ? what I thought was the error ?
    #include <stdio.h>
             ^~~~~~~~~
    1 error generated.

    It appears you are missing some prerequisite to build the package 


What I did so far, without fixing anything:

  • xcode-select --install
  • installed xcode
  • open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Still the same error on stdio.h.

which exists in a number of places:

(venv) jluc@bemyerp$ mdfind -name stdio.h
/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/sys/stdio.h
/usr/include/_stdio.h
/usr/include/secure/_stdio.h
/usr/include/stdio.h  ?  I believe this is the one that's usually missing.
                            but I have it.
/usr/include/sys/stdio.h
/usr/include/xlocale/_stdio.h

So, let's go to that first directory clang is complaining about and look:

(venv) jluc@gotchas$ cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs
(venv) jluc@SDKs$ ls -l
total 0
drwxr-xr-x  8 root  wheel  256 Aug 29 23:47 MacOSX.sdk
drwxr-xr-x  4 root  wheel  128 Aug 29 23:47 DriverKit19.0.sdk
drwxr-xr-x  6 root  wheel  192 Sep 11 04:47 ..
lrwxr-xr-x  1 root  wheel   10 Oct  1 13:28 MacOSX10.15.sdk -> MacOSX.sdk  
drwxr-xr-x  5 root  wheel  160 Oct  1 13:34 .

Hah, we have a symlink for MacOSX10.15.sdk, but none for MacOSX10.14.sdk. Here's my first clang error again:

clang: warning: no such sysroot directory: '/Applications/Xcode.app/.../Developer/SDKs/MacOSX10.14.sdk' [-Wmissing-sysroot]

My guess is Apple jumped the gun on their xcode config and are already thinking they're on Catalina. Since it's a new Mac, the old config for 10.14 is not in place.

THE FIX:

Let's symlink 10.14 the same way as 10.15:

ln -s MacOSX.sdk/ MacOSX10.14.sdk

btw, if I go to that sdk directory, I find:

...
./usr/include/sys/stdio.h
./usr/include/stdio.h
....

OUTCOME:

pip install psycopg2 works.

Note: the actual pip install command made no reference to MacOSX10.14.sdk, that came at a later point, possibly by the Python installation mechanism introspecting the OS version.

Data-frame Object has no Attribute

data=pd.read_csv('/your file name', delim_whitespace=True)

data.Number

now you can run this code with no error.

Add & delete view from Layout

I've done it like so:

((ViewManager)entry.getParent()).removeView(entry);

How to increase apache timeout directive in .htaccess?

This solution is for Litespeed Server (Apache as well)

Add the following code in .htaccess

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

Litespeed reference

Do subclasses inherit private fields?

No. Private fields are not inherited... and that's why Protected was invented. It is by design. I guess this justified the existence of protected modifier.


Now coming to the contexts. What you mean by inherited -- if it is there in the object created from derived class? yes, it is.

If you mean can it be useful to derived class. Well, no.

Now, when you come to functional programming the private field of super class is not inherited in a meaningful way for the subclass. For the subclass, a private field of super class is same as a private field of any other class.

Functionally, it's not inherited. But ideally, it is.


OK, just looked into Java tutorial they quote this:

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

refer: http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

I agree, that the field is there. But, subclass does not get any privilege on that private field. To a subclass, the private field is same as any private field of any other class.

I believe it's purely matter of point-of-view. You may mould the argument either side. It's better justify both way.

 

What exactly is the 'react-scripts start' command?

As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

"scripts": {
  "start": "npm-run-all -p watch-css start-js",
  "build": "npm run build-css && react-scripts build",
  "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
  "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
  "start-js": "react-scripts start"
},

For clarity, I added a diagram. enter image description here

The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

  • npm run start
  • npm run build

The grey boxes are commands which can be executed from the command line.

So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

  • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

  • The start-js points to the react-scripts start which hosts the website in a development mode.

In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

How to compare two date values with jQuery

just use the jQuery datepicker UI library and convert both your strings into date format, then you can easily compare. following link might be useful

https://stackoverflow.com/questions/2974496/jquery-javascript-convert-date-string-to-date

cheers..!!

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

I know the question doesn't state SQL Server express, but its worth pointing out that the SQL Server Express editions don't come with the profiler (very annoying), and I suspect that they also don't come with the query analyzer.

psql - save results of command to a file

COPY tablename TO '/tmp/output.csv' DELIMITER ',' CSV HEADER;

this command is used to store the entire table as csv

MessageBodyWriter not found for media type=application/json

You've to create empty constructor because JAX-RS initializes the classes... Your constructor must have no arguments:

@XmlRootElement
public class Student implements Serializable {

    public String first_name;
    public String last_name;

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public Student()
    {
        first_name = "Fahad";
        last_name = "Mullaji";
    }


 public Student()
    {
    }
}

Check if Internet Connection Exists with jQuery?

A much simpler solution:

<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>

and later in the code:

var online;
// check whether this function works (online only)
try {
  var x = google.maps.MapTypeId.TERRAIN;
  online = true;
} catch (e) {
  online = false;
}
console.log(online);

When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

Remove all special characters except space from a string using JavaScript

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ??????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

How do I list loaded plugins in Vim?

:set runtimepath?

This lists the path of all plugins loaded when a file is opened with Vim.

How to change the color of an image on hover

If I understand correctly then it would be easier if you gave your image a transparent background and set the background container's background-color property without having to use filters and so on.

http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html

Shows you how to use filters in IE. Maybe if you leverage something from that. Not very cross-browser compatible though. Another option might be to have two images and use them as background-images (rather than img tags), swap one out after another using the :hover pseudo selector.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

In my case adding Preamble to file solved my problem:

var data = Encoding.UTF8.GetBytes(csv);
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
return File(new MemoryStream(result), "application/octet-stream", "data.csv");

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

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

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

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

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

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

Which yields

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

When to use the different log levels

I suggest using only three levels

  1. Fatal - Which would break the application.
  2. Info - Info
  3. Debug - Less important info

How to use '-prune' option of 'find' in sh?

Adding to the advice given in other answers (I have no rep to create replies)...

When combining -prune with other expressions, there is a subtle difference in behavior depending on which other expressions are used.

@Laurence Gonsalves' example will find the "*.foo" files that aren't under ".snapshot" directories:-

find . -name .snapshot -prune -o -name '*.foo' -print

However, this slightly different short-hand will, perhaps inadvertently, also list the .snapshot directory (and any nested .snapshot directories):-

find . -name .snapshot -prune -o -name '*.foo'

The reason is (according to the manpage on my system):-

If the given expression does not contain any of the primaries -exec, -ls, -ok, or -print, the given expression is effectively replaced by:

( given_expression ) -print

That is, the second example is the equivalent of entering the following, thereby modifying the grouping of terms:-

find . \( -name .snapshot -prune -o -name '*.foo' \) -print

This has at least been seen on Solaris 5.10. Having used various flavors of *nix for approx 10 years, I've only recently searched for a reason why this occurs.

Declaring abstract method in TypeScript

If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:

/**
 * The interface defines all abstract methods and extends the concrete base class
 */
interface IAnimal extends Animal {
    speak() : void;
}

/**
 * The abstract base class only defines concrete methods & properties.
 */
class Animal {

    private _impl : IAnimal;

    public name : string;

    /**
     * Here comes the clever part: by letting the constructor take an 
     * implementation of IAnimal as argument Animal cannot be instantiated
     * without a valid implementation of the abstract methods.
     */
    constructor(impl : IAnimal, name : string) {
        this.name = name;
        this._impl = impl;

        // The `impl` object can be used to delegate functionality to the
        // implementation class.
        console.log(this.name + " is born!");
        this._impl.speak();
    }
}

class Dog extends Animal implements IAnimal {
    constructor(name : string) {
        // The child class simply passes itself to Animal
        super(this, name);
    }

    public speak() {
        console.log("bark");
    }
}

var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"

Since the Animal class requires an implementation of IAnimal it's impossible to construct an object of type Animal without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal, not Animal. E.g.:

//This works
function letTheIAnimalSpeak(animal: IAnimal) {
    console.log(animal.name + " says:");
    animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
    console.log(animal.name + " says:");
    animal.speak();
}

The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.

Unresolved Import Issues with PyDev and Eclipse

In the properties for your pydev project, there's a pane called "PyDev - PYTHONPATH", with a sub-pane called "External Libraries". You can add source folders (any folder that has an __init__.py) to the path using that pane. Your project code will then be able to import modules from those source folders.

Storing images in SQL Server?

When storing images in SQL Server do not use the 'image' datatype, according to MS it is being phased out in new versions of SQL server. Use varbinary(max) instead

https://msdn.microsoft.com/en-us/library/ms187993.aspx

Compiling with g++ using multiple cores

GNU parallel

I was making a synthetic compilation benchmark and couldn't be bothered to write a Makefile, so I used:

sudo apt-get install parallel
ls | grep -E '\.c$' | parallel -t --will-cite "gcc -c -o '{.}.o' '{}'"

Explanation:

  • {.} takes the input argument and removes its extension
  • -t prints out the commands being run to give us an idea of progress
  • --will-cite removes the request to cite the software if you publish results using it...

parallel is so convenient that I could even do a timestamp check myself:

ls | grep -E '\.c$' | parallel -t --will-cite "\
  if ! [ -f '{.}.o' ] || [ '{}' -nt '{.}.o' ]; then
    gcc -c -o '{.}.o' '{}'
  fi
"

xargs -P can also run jobs in parallel, but it is a bit less convenient to do the extension manipulation or run multiple commands with it: Calling multiple commands through xargs

Parallel linking was asked at: Can gcc use multiple cores when linking?

TODO: I think I read somewhere that compilation can be reduced to matrix multiplication, so maybe it is also possible to speed up single file compilation for large files. But I can't find a reference now.

Tested in Ubuntu 18.10.

How do I write a RGB color value in JavaScript?

Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:

function rgb(r, g, b){
  return "rgb("+r+","+g+","+b+")";
}

Alternatively (to create fewer string objects), you could use array join():

function rgb(r, g, b){
  return ["rgb(",r,",",g,",",b,")"].join("");
}

The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:

function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}

You could also use ES6 language features:

const rgb = (r, g, b) => 
  `rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;

Why can't I inherit static classes?

Think about it this way: you access static members via type name, like this:

MyStaticType.MyStaticMember();

Were you to inherit from that class, you would have to access it via the new type name:

MyNewType.MyStaticMember();

Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.

Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.

Perhaps you want to add methods to an existing static type. You can do that already via extension methods.

Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.

So, in the end you don't really gain anything from inheriting static classes.

HttpURLConnection timeout settings

You can set timeout like this,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);

How to access SVG elements with Javascript

In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {

    //alert("Document loaded, including graphics and embedded documents (like SVG)");
    var a = document.getElementById("alphasvg");

    //get the inner DOM of alpha.svg
    var svgDoc = a.contentDocument;

    //get the inner element by id
    var delta = svgDoc.getElementById("delta");
    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});

NHibernate.MappingException: No persister for: XYZ

I had similar problem, and I solved it as folows:

I working on MS SQL 2008, but in the NH configuration I had bad dialect: NHibernate.Dialect.MsSql2005Dialect if I correct it to: NHibernate.Dialect.MsSql2008Dialect then everything's working fine without a exception "No persister for: ..." David.

SQL- Ignore case while searching for a string

See this similar question and answer to searching with case insensitivity - SQL server ignore case in a where expression

Try using something like:

SELECT DISTINCT COL_NAME 
FROM myTable 
WHERE COL_NAME COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%priceorder%'

Flex-box: Align last row to grid

This is a combination of a lot of the answers but it does exactly what I was needing -- which is, aligning the last child in a flex container to the left while maintaining the space-between behavior (in this case it's a three-column layout).

Here's the markup:

.flex-container {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}

.flex-container:after {
  content: "";
  flex-basis: 30%;
}

Scroll to a specific Element Using html

_x000D_
_x000D_
 <nav>
      <a href="#section1">1</a> 
      <a href="#section2">2</a> 
      <a href="#section3">3</a>
    </nav>
    <section id="section1">1</section>
    <section id="section2" class="fifty">2</section>
    <section id="section3">3</section>
    
    <style>
      * {padding: 0; margin: 0;}
      nav {
        background: black;
        position: fixed;
      }
      a {
        color: #fff;
        display: inline-block;
        padding: 0 1em;
        height: 50px;
      }
      section {
        background: red;
        height: 100vh;
        text-align: center;
        font-size: 5em;
      }
      html {
        scroll-behavior: smooth;
      }
      #section1{
        background-color:green;
      }
      #section3{
        background-color:yellow;
      }
      
    </style>
    
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" >
      $(document).on('click', 'a[href^="#"]', function (event) {
        event.preventDefault();
    
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top
        }, 500);
      });
    </script>
      
_x000D_
_x000D_
_x000D_

How to handle errors with boto3?

  • Only one import needed.
  • No if statement needed.
  • Use the client built-in exception as intended.

Ex:

from boto3 import client

cli = client('iam')
try:
    cli.create_user(
        UserName = 'Brian'
    )
except cli.exceptions.EntityAlreadyExistsException:
    pass

a CloudWatch example:

cli = client('logs')
try:
    cli.create_log_group(
        logGroupName = 'MyLogGroup'
    )
except cli.exceptions.ResourceAlreadyExistsException:
    pass

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1

Go back button in a page

You can either use:

<button onclick="window.history.back()">Back</button>

or..

<button onclick="window.history.go(-1)">Back</button>

The difference, of course, is back() only goes back 1 page but go() goes back/forward the number of pages you pass as a parameter, relative to your current page.

How to open Atom editor from command line in OS X?

In addition to @sbedulin (Greeting, lovely Windows users!)

The general path on Windows should be

%USERPROFILE%\AppData\Local\atom\bin

If you are using a bash emulator like babun. You'd better checkout the shell files, which only available in the real app folders

/c/User/<username>/AppData/Local/atom/app-<version>/resources/cli/apm.sh # or atom.sh

Excel Validation Drop Down list using VBA

The accepted answer is correct but needs to be wary that this way imposes a 255 character limit. Better to reference an actual worksheet range object.

When is the finalize() method called in Java?

Sometimes when it is destroyed, an object must make an action. For example, if an object has a non-java resource such as a file handle or a font, you can verify that these resources are released before destroying an object. To manage such situations, java offers a mechanism called "finalizing". By finalizing it, you can define specific actions that occur when an object is about to be removed from the garbage collector. To add a finalizer to a class simply define the finalize() method. Java execution time calls this method whenever it is about to delete an object of that class. Within the finalize method() you specify actions to be performed before destroying an object. The garbage collector is periodically searched for objects that no longer refer to any running state or indirectly any other object with reference. Before an asset is released, the Java runtime calls the finalize() method on the object. The finalize() method has the following general form:

protected void finalize(){
    // This is where the finalization code is entered
}

With the protected keyword, access to finalize() by code outside its class is prevented. It is important to understand that finalize() is called just just before the garbage collection. It is not called when an object leaves the scope, for example. It means you can not know when, or if, finalize() will be executed. As a result, the program must provide other means to free system resources or other resources used by the object. You should not rely on finalize() for normal running of the program.

Class 'ViewController' has no initializers in swift

The error could be improved, but the problem with your first version is you have a member variable, delegate, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.

When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.

How to merge specific files from Git branches

I am in same situation, I want to merge a file from a branch which has many commits on it on 2 branch. I tried many ways above and other I found on the internet and all failed (because commit history is complex) so I decide to do my way (the crazy way).

git merge <other-branch>
cp file-to-merge file-to-merge.example
git reset --hard HEAD (or HEAD^1 if no conflicts happen)
cp file-to-merge.example file-to-merge

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

The accepted answer is great, but here's the short answer:

<key>CFBundleIconFiles</key>
<array>
    <string>[email protected]</string>
    <string>icon.png</string>
    <string>Icon-Small.png</string>
    <string>[email protected]</string>
    <string>Default.png</string>
    <string>[email protected]</string>
    <string>icon-72.png</string>
    <string>[email protected]</string>
    <string>Icon-Small-50.png</string>
    <string>[email protected]</string>
    <string>Default-Landscape.png</string>
    <string>[email protected]</string>
    <string>Default-Portrait.png</string>
    <string>[email protected]</string>

New icons below here

    <string>icon-40.png</string>
    <string>[email protected]</string>
    <string>icon-60.png</string>
    <string>[email protected]</string>
    <string>icon-76.png</string>
    <string>[email protected]</string>
</array>

Found this here by searching for "The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format." in Google.

Align text to the bottom of a div

You now can do this with Flexbox justify-content: flex-end now:

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
  align-items: flex-end;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  border: solid 1px red;_x000D_
}_x000D_
  
_x000D_
<div>_x000D_
  Something to align_x000D_
</div>
_x000D_
_x000D_
_x000D_

Consult your Caniuse to see if Flexbox is right for you.

How do I get the find command to print out the file size with the file name?

You could try this:

find. -name *.ear -exec du {} \;

This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like

5000  ./dir1/dir2/earFile1.ear
5400  ./dir1/dir2/earFile2.ear
5400  ./dir1/dir3/earFile1.ear

How do I retrieve a textbox value using JQuery?

You need to use the val() function to get the textbox value. text does not exist as a property only as a function and even then its not the correct function to use in this situation.

var from = $("input#fromAddress").val()

val() is the standard function for getting the value of an input.

syntax error: unexpected token <

Just ignore parameter passing as a false in java script functions

Ex:

function getCities(stateId,locationId=false){    

    // Avoid writting locationId= false kind of statements
   /*your code comes here*/

 }

Avoid writting locationId= false kind of statements, As this will give the error in chrome and IE

How to obtain the last index of a list?

len(list1)-1 is definitely the way to go, but if you absolutely need a list that has a function that returns the last index, you could create a class that inherits from list.

class MyList(list):
    def last_index(self):
        return len(self)-1


>>> l=MyList([1, 2, 33, 51])
>>> l.last_index()
3

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Sample DDL

create table #Temp
(
    EventID int, 
    EventTitle Varchar(50), 
    EventStartDate DateTime, 
    EventEndDate DatetIme, 
    EventEnumDays int,
    EventStartTime Datetime,
    EventEndTime DateTime, 
    EventRecurring Bit, 
    EventType int
)

;WITH Calendar
AS (SELECT /*...*/)

Insert Into #Temp
Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
    or EventEnumDays is null

Make sure that the table is deleted after use

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

Batch file to map a drive when the folder name contains spaces

I'm not sure this will help you to much by I once needed a batch file to open a game, the .exe was in a folder with blanks (duh!) and I tried : START "C:\Fold 1\fold 2\game.exe" and START C:\Fold 1\fold 2\game.exe - None worked, then I tried

   START C:\"Fold 1"\"fold 2"\game.exe and it worked 

Hope it helps :)

How to print to console using swift playground?

As of Xcode 7.0.1 println is change to print. Look at the image. there are lot more we can print out. enter image description here

Convert stdClass object to array in PHP

For one-dimensional arrays:

$array = (array)$class; 

For multi-dimensional array:

function stdToArray($obj){
  $reaged = (array)$obj;
  foreach($reaged as $key => &$field){
    if(is_object($field))$field = stdToArray($field);
  }
  return $reaged;
}

How can I pop-up a print dialog box using Javascript?

window.print();  

unless you mean a custom looking popup.

Android: Quit application when press back button

Instead of finish() call super.onBackPressed()

How to remove undefined and null values from an object using lodash?

For those of you getting here looking to remove from an array of objects and using lodash you can do something like this:


 const objects = [{ a: 'string', b: false, c: 'string', d: undefined }]
 const result = objects.map(({ a, b, c, d }) => _.pickBy({ a,b,c,d }, _.identity))

 // [{ a: 'string', c: 'string' }]

Note: You don't have to destruct if you don't want to.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

Use serialize and deserialize methods in SerializationUtils from commons-lang.

How do I make a textbox that only accepts numbers?

It seems like many of the current answers to this question are manually parsing the input text. If you're looking for a specific built-in numeric type (e.g. int or double), why not just delegate the work to that type's TryParse method? For example:

public class IntTextBox : TextBox
{
    string PreviousText = "";
    int BackingResult;

    public IntTextBox()
    {
        TextChanged += IntTextBox_TextChanged;
    }

    public bool HasResult { get; private set; }

    public int Result
    {
        get
        {
            return HasResult ? BackingResult : default(int);
        }
    }

    void IntTextBox_TextChanged(object sender, EventArgs e)
    {
        HasResult = int.TryParse(Text, out BackingResult);

        if (HasResult || string.IsNullOrEmpty(Text))
        {
            // Commit
            PreviousText = Text;
        }
        else
        {
            // Revert
            var changeOffset = Text.Length - PreviousText.Length;
            var previousSelectionStart =
                Math.Max(0, SelectionStart - changeOffset);

            Text = PreviousText;
            SelectionStart = previousSelectionStart;
        }
    }
}

If you want something more generic but still compatible with Visual Studio's Designer:

public class ParsableTextBox : TextBox
{
    TryParser BackingTryParse;
    string PreviousText = "";
    object BackingResult;

    public ParsableTextBox()
        : this(null)
    {
    }

    public ParsableTextBox(TryParser tryParse)
    {
        TryParse = tryParse;

        TextChanged += ParsableTextBox_TextChanged;
    }

    public delegate bool TryParser(string text, out object result);

    public TryParser TryParse
    {
        set
        {
            Enabled = !(ReadOnly = value == null);

            BackingTryParse = value;
        }
    }

    public bool HasResult { get; private set; }

    public object Result
    {
        get
        {
            return GetResult<object>();
        }
    }

    public T GetResult<T>()
    {
        return HasResult ? (T)BackingResult : default(T);
    }

    void ParsableTextBox_TextChanged(object sender, EventArgs e)
    {
        if (BackingTryParse != null)
        {
            HasResult = BackingTryParse(Text, out BackingResult);
        }

        if (HasResult || string.IsNullOrEmpty(Text))
        {
            // Commit
            PreviousText = Text;
        }
        else
        {
            // Revert
            var changeOffset = Text.Length - PreviousText.Length;
            var previousSelectionStart =
                Math.Max(0, SelectionStart - changeOffset);

            Text = PreviousText;
            SelectionStart = previousSelectionStart;
        }
    }
}

And finally, if you want something fully generic and don't care about Designer support:

public class ParsableTextBox<T> : TextBox
{
    TryParser BackingTryParse;
    string PreviousText;
    T BackingResult;

    public ParsableTextBox()
        : this(null)
    {
    }

    public ParsableTextBox(TryParser tryParse)
    {
        TryParse = tryParse;

        TextChanged += ParsableTextBox_TextChanged;
    }

    public delegate bool TryParser(string text, out T result);

    public TryParser TryParse
    {
        set
        {
            Enabled = !(ReadOnly = value == null);

            BackingTryParse = value;
        }
    }

    public bool HasResult { get; private set; }

    public T Result
    {
        get
        {
            return HasResult ? BackingResult : default(T);
        }
    }

    void ParsableTextBox_TextChanged(object sender, EventArgs e)
    {
        if (BackingTryParse != null)
        {
            HasResult = BackingTryParse(Text, out BackingResult);
        }

        if (HasResult || string.IsNullOrEmpty(Text))
        {
            // Commit
            PreviousText = Text;
        }
        else
        {
            // Revert
            var changeOffset = Text.Length - PreviousText.Length;
            var previousSelectionStart =
                Math.Max(0, SelectionStart - changeOffset);

            Text = PreviousText;
            SelectionStart = previousSelectionStart;
        }
    }
}

Why use Optional.of over Optional.ofNullable?

Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.

Which is the preferred way to concatenate a string in Python?

If you are concatenating a lot of values, then neither. Appending a list is expensive. You can use StringIO for that. Especially if you are building it up over a lot of operations.

from cStringIO import StringIO
# python3:  from io import StringIO

buf = StringIO()

buf.write('foo')
buf.write('foo')
buf.write('foo')

buf.getvalue()
# 'foofoofoo'

If you already have a complete list returned to you from some other operation, then just use the ''.join(aList)

From the python FAQ: What is the most efficient way to concatenate many strings together?

str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)

(another reasonably efficient idiom is to use io.StringIO)

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray()
for b in my_bytes_objects:
    result += b

Edit: I was silly and had the results pasted backwards, making it look like appending to a list was faster than cStringIO. I have also added tests for bytearray/str concat, as well as a second round of tests using a larger list with larger strings. (python 2.7.3)

ipython test example for large lists of strings

try:
    from cStringIO import StringIO
except:
    from io import StringIO

source = ['foo']*1000

%%timeit buf = StringIO()
for i in source:
    buf.write(i)
final = buf.getvalue()
# 1000 loops, best of 3: 1.27 ms per loop

%%timeit out = []
for i in source:
    out.append(i)
final = ''.join(out)
# 1000 loops, best of 3: 9.89 ms per loop

%%timeit out = bytearray()
for i in source:
    out += i
# 10000 loops, best of 3: 98.5 µs per loop

%%timeit out = ""
for i in source:
    out += i
# 10000 loops, best of 3: 161 µs per loop

## Repeat the tests with a larger list, containing
## strings that are bigger than the small string caching 
## done by the Python
source = ['foo']*1000

# cStringIO
# 10 loops, best of 3: 19.2 ms per loop

# list append and join
# 100 loops, best of 3: 144 ms per loop

# bytearray() +=
# 100 loops, best of 3: 3.8 ms per loop

# str() +=
# 100 loops, best of 3: 5.11 ms per loop

How to call external JavaScript function in HTML

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here

How can I switch word wrap on and off in Visual Studio Code?

  • Mac: Code -> Preferences -> Settings -> Type wordwrap in Search settings -> Change Editor: Word Wrap from off to on.

  • Windows: File -> Preferences -> Settings -> Type wordwrap in Search settings -> Change Editor: Word Wrap from off to on.

Property 'value' does not exist on type EventTarget in TypeScript

I was looking for a solution to a similar TypeScript error with React:

Property 'dataset' does not exist on type EventTarget in TypeScript

I wanted to get to event.target.dataset of a clicked button element in React:

<button
  onClick={onClickHandler}
  data-index="4"
  data-name="Foo Bar"
>
  Delete Candidate
</button>

Here is how I was able to get the dataset value to "exist" via TypeScript:

const onClickHandler = (event: React.MouseEvent<HTMLButtonElement>) => {
  const { name, index } = (event.target as HTMLButtonElement).dataset
  console.log({ name, index })
  // do stuff with name and index…
}

Maximum and Minimum values for ints

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don't need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.

init-param and context-param

<init-param> will be used if you want to initialize some parameter for a particular servlet. When request come to servlet first its init method will be called then doGet/doPost whereas if you want to initialize some variable for whole application you will need to use <context-param> . Every servlet will have access to the context variable.

How to read user input into a variable in Bash?

Also you can try zenity !

user=$(zenity --entry --text 'Please enter the username:') || exit 1